【问题标题】:Junit test with autowired fields具有自动装配字段的 Junit 测试
【发布时间】:2014-10-29 18:28:05
【问题描述】:

我正在为一个类编写一系列测试用例,其中包含以下几种方法:

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

我觉得这违背了单元测试的意义,因为它只是返回我告诉它的内容,而不是真正做任何其他事情。

【问题讨论】:

  • 向我们展示该字段是如何自动连接的。你使用字段注入、构造函数注入还是 setter 注入?
  • @JBNizet 它使用字段注入。 @Autowired private RestTemplate restTemplate;

标签: java spring junit mockito autowired


【解决方案1】:

由于您选择了字段注入,因此在对象中注入模拟依赖项的唯一方法是使用反射。如果你改用构造函数注入,那就简单了

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

【讨论】:

  • 效果很好。我想我现在正在圈子里工作,因为看来我无论如何都需要模拟一个响应(restTemplate.getForObject(getGroupServiceURL(), UWLevel[].class))。这回答了我的问题,所以谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 2020-02-09
  • 1970-01-01
  • 2016-02-23
  • 2021-12-23
相关资源
最近更新 更多