[英]Junit test with autowired fields
I am writing a series of test cases for a class with a few methods like: 我正在使用几种方法为类编写一系列测试用例:
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;
}
The problem I am having is the fact that the restTemplate
is @autowired
from the actual implementation of the class (and therefore returning null when called in the unit test perspective). 我遇到的问题是,
restTemplate
是从类的实际实现中@autowired
的(因此在单元测试透视图中调用时返回null)。 How would I go about writing a proper test case for these methods? 我将如何为这些方法编写适当的测试用例?
Here is what I have tried so far: 到目前为止,这是我尝试过的:
@Test
public void testGetListOfGroups() {
//TODO
ServiceResponse resp = new ServiceResponse();
Mockito.when(uwsci.getListOfGroups()).thenReturn(resp); //uwsci is my mocked object
assertTrue(uwsci.getListOfGroups() == resp);
}
I feel that this defeats the point of unit testing as it is just returning what I told it to and not really doing anything else. 我觉得这超出了单元测试的目的,因为它只是返回我告诉的内容,而没有做任何其他事情。
Since you chose field injection, the only way to inject a mock dependency in your object is to use reflection. 由于您选择了字段注入,因此在对象中注入模拟依赖项的唯一方法是使用反射。 If you had used constructor injection instead, it would be as easy as
如果您改用构造函数注入,那将很容易
RestTemplate mockRestTemplate = mock(RestTemplate.class);
ClassUnderTest c = new ClassUnderTest(mockRestTemplate);
Fortunately, Mockito makes that possible using its annotations support: 幸运的是,Mockito使用其注释支持使之成为可能:
@Mock
private RestTemplate mockRestTemplate;
@InjectMocks
private ClassUnderTest classUnderTest;
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.