【问题标题】:Unit test service class with mocks using TestNG使用 TestNG 模拟单元测试服务类
【发布时间】:2019-05-21 04:19:23
【问题描述】:

我正在尝试为通用服务类编写单元测试,如下所示:

public class ApiService{
    private RestTemplate restTemplate;

    private ServiceDao serviceDao;


    @Autowired
    public ApiService(RestTemplate restTemplate, ServiceDao serviceDao) {
        this.restTemplate = restTemplate;
        this.serviceDao = serviceDao;
    }

    public ResponseEntity getObject(ObjectRequest request) {
        // Service logic here
    }

    public ResponseEntity postObject(CreateObjectRequest request) {
        // Service logic here
    }
}

但是我正在努力如何在我的服务类的构造函数中模拟 restTemplate,这样当测试运行时,数据不会被持久化。我研究了 Mockito 虽然没有看到很多关于 Mockito + 的示例或文档TestNG 在这种情况下。任何帮助将不胜感激

【问题讨论】:

标签: java unit-testing spring-boot testng


【解决方案1】:

首先 - 如果可能的话,在您的服务中注入 RestOperations 而不是 RestTemplate。然后你就可以轻松地模拟它的行为(注意:RestTemplate 实现了 RestOperations)。

如果无法使用 RestOperations - 你可以这样做:

RestTemplate myTemplate = Mockito.spy(new RestTemplate());
String expectedOutput = "hello mock";
String inputUrl = "https://stackoverflow.com/questions/53872148/unit-test-service-class-with-mocks-using-testng";
Mockito.doReturn(expectedOutput).when(myTemplate).getForObject(inputUrl, String.class);
String result = myTemplate.getForObject(inputUrl, String.class);
Assert.assertEquals(expectedOutput, result);

【讨论】:

  • 这是有道理的。我感到困惑的部分是如何模拟这一行 Mockito.doReturn(expectedOutput).when(myTemplate).getForObject(inputUrl, String.class);因为这个 getForObject 调用是在 dao 层中抽象出来的(在我的服务类中传递了 restTemplate 对象)
【解决方案2】:

我实际上已经使用 Mockito 构建了一个方法,如下所示......可能有一个更优雅的解决方案,所以我很想看看:

public class ServiceTest {

    @BeforeMethod(groups="serviceTest")
    public void beforeMethod() {
        MockitoAnnotations.initMocks(this);
    }


    @Test(groups="serviceTest")
    public void testGetService_returns200() {
        when(serviceDao.getService(any(String.class), any(RestTemplate.class), any(HttpHeaders.class))).thenReturn(new ResponseEntity(new Object(), HttpStatus.OK));

        ObjectRequest request = new ObjectRequest();
        // set request values
        ResponseEntity testResponse = apiService.getObject(request);

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多