我使用几种方法为类编写了一系列测试用例:
public ServiceResponse getListOfGroups() {
ServiceResponse serviceResponse = new ServiceResponse();
try{
Slf4JStopWatch sw = new Slf4JStopWatch("GetListOfGroups", log, DEBUG_LEVEL);
List<Group> Groups = Arrays.asList(restTemplate.getForObject(getGroupServiceURL(), Group[].class));
sw.stop();
serviceResponse.setData(Groups);
} catch(ServiceException ex) {
serviceResponse.setErrorObject(ex.getErrorObject());
}
return serviceResponse;
}
我遇到的问题是事实,restTemplate
是@autowired
从实际执行的类的(因此返回null在单元测试的角度调用时)。我将如何为这些方法编写适当的测试用例?
到目前为止,这是我尝试过的:
@Test
public void testGetListOfGroups() {
//TODO
ServiceResponse resp = new ServiceResponse();
Mockito.when(uwsci.getListOfGroups()).thenReturn(resp); //uwsci is my mocked object
assertTrue(uwsci.getListOfGroups() == resp);
}
我觉得这超出了单元测试的目的,因为它只是返回我告诉的内容,而没有真正做任何其他事情。
由于选择了字段注入,因此在对象中注入模拟依赖项的唯一方法是使用反射。如果您改用构造函数注入,那将很容易
RestTemplate mockRestTemplate = mock(RestTemplate.class);
ClassUnderTest c = new ClassUnderTest(mockRestTemplate);
幸运的是,Mockito使用其注释支持使之成为可能:
@Mock
private RestTemplate mockRestTemplate;
@InjectMocks
private ClassUnderTest classUnderTest;
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句