【发布时间】:2018-10-22 15:17:53
【问题描述】:
我正在为 REST API 编写集成测试。我在测试时遇到问题 MyService 类中 validateDate 的逻辑。我想模拟 currentDate() 方法 MyService 类以编写不同的测试场景。如何在 Spring Boot 中实现这一点?
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyControllerTest {
TestRestTemplate restTemplate = new TestRestTemplate();
@LocalServerPort
private int port;
//@MockBean
//MyService service;
@Test
public void testRetrieveStudentCourse() {
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<String>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(
createURLWithPort("/validatedate"),
HttpMethod.GET, entity, String.class);
String expected = "true";
assertEquals(expected, response.getBody(), false);
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
import java.util.Date;
import org.springframework.stereotype.Service;
public interface IMyService {
public boolean validateDate(Date date);
}
@Service
public class MyService implements IMyService{
public boolean validateDate(Date date) {
if(currentDate().before(date)) {
return true;
}
return false;
}
private Date currentDate() {
return new Date();
}
}
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
IMyService service;
@GetMapping(value = "/validatedate", produces = MediaType.APPLICATION_JSON_VALUE)
public boolean validateDate() {
// date object will be retrieved.
Date date = somedate;
service.validateDate(date);
}
}
Mockito.when(myservice.currentDate()).thenReturn(null);
doReturn(null).when(myservice.currentDate());
【问题讨论】:
-
为什么
@MockBean和目标测试中的后续存根对您不起作用? -
我测试了@Mockbean,然后服务类中的方法validateDate()没有执行。可能是我缺乏知识。
-
好的。如果您希望调用真正的方法,请考虑改用
@SpyBean。然后存根应该做一个InvocationOnMock.callRealMethod() -
@Artem。谢谢你。调用即将到来的方法。但我无法更改 currentDate() 的值。总是给出 currentDate。我想将日期模拟为空,并将昨天的日期和明天的日期模拟为 testng 场景。
-
好吧,你不能存根
private方法。确实如此。也许考虑将该方法也设为public?
标签: spring-mvc spring-boot integration-testing