![](/img/trans.png)
[英]Injecting non-mocks defined by a @Configuration class into a unit test
[英]Unit test service class with mocks using TestNG
我正在尝试为通用服务类编写单元测试,如下所示:
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 + TestNG的示例或文档,但我一直在研究Mockito。上下文。 任何帮助,将不胜感激
首先-如果可能的话,在您的服务中注入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构造了一种方法,如下所示:可能会有一个更优雅的解决方案,所以我很想看看:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.