Aar*_*n C 1 java junit spring mockito autowired
我正在为一个类编写一系列测试用例,其中包括以下几种方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,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);
}
Run Code Online (Sandbox Code Playgroud)
我觉得这会破坏单元测试的重点,因为它只是返回我告诉它的内容而不是真正做其他任何事情.
由于您选择了字段注入,因此在对象中注入模拟依赖项的唯一方法是使用反射.如果你曾经使用过构造函数注入,那就简单了
RestTemplate mockRestTemplate = mock(RestTemplate.class);
ClassUnderTest c = new ClassUnderTest(mockRestTemplate);
Run Code Online (Sandbox Code Playgroud)
幸运的是,Mockito使用其注释支持使这成为可能:
@Mock
private RestTemplate mockRestTemplate;
@InjectMocks
private ClassUnderTest classUnderTest;
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1557 次 |
| 最近记录: |