繁体   English   中英

使用自动连接字段进行Junit测试

[英]Junit test with autowired fields

我正在使用几种方法为类编写一系列测试用例:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM