我们的网络服务在他们的一端更新。我使用 Spring Web 服务更新了我们的客户端代码。
问题是单元测试在返回时失败,因为注入的模拟 WebServiceTemplate 返回 null。
我的问题是"有没有办法使返回一些预定义的值?
@Configuration
public class TestConfig {
@Bean
public WebServiceTemplate webServiceTemplate() {
WebServiceTemplate webServiceTemplate = mock(WebServiceTemplate.class);
return webServiceTemplate;
}
@Bean
public TheServiceClient client() {
return new TheServiceClient();
}
}
public class TheServiceClient {
@Autowired
private WebServiceTemplate webServiceTemplate;
public TheResponse getResponse(TheRequest request) {
// logic handles the request need to be tested
JAXBElement<?> element = (JAXBElement<?>) webServiceTemplate.marshalSendAndReceive(request);
return element.getResponse();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class IdalClientTest {
@Autowired
private TheServiceClient client;
@Test
public void testGetResponse() {
TheRequest request = new TheRequest();
request.setters();
TheResponse response = client.getResponse(request);
assertThat(response.getSucess()).isTrue();
}
}
因为你没有将模拟的WebServiceTemplate注入到TheServiceClient。
你应该这样做
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class IdalClientTest {
@InjectMocks
private TheServiceClient client;
@Mock
WebServiceTemplate webServiceTemplate;
@Mock
JAXBElement jaxBElement;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(webServiceTemplate.marshalSendAndReceive(any(TheRequest.class))).thenReturn(jaxBElement);
// You can create a TheResponse object with success = true;
when(jaxBElement.getResponse()).thenReturn(dummyTheResponseObject);
}
@Test
public void testGetResponse() {
TheRequest request = new TheRequest();
request.setters();
TheResponse response = client.getResponse(request);
assertThat(response.getSucess()).isTrue();
}
}
您不需要该配置类。
理想的方法是使用构造函数注入而不是字段注入。喜欢这个
public class TheServiceClient {
private final WebServiceTemplate webServiceTemplate;
@Autowired
public TheServiceClient(final WebServiceTemplate webServiceTemplate) {
this.webServiceTemplate = webServiceTemplate;
}
.......
}
然后在你的测试类而不是InjectMocks中,你可以这样做
private TheServiceClient client;
@Mock
WebServiceTemplate webServiceTemplate;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
client = new TheServiceClient(webServiceTemplate);
.............
}
................