【发布时间】:2022-01-11 18:26:06
【问题描述】:
当使用MockRestServiceServer 和andExpect 进行测试时
mockServer.expect(requestTo("/hotels/42")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess("{ \"id\" : \"42\", \"name\" : \"Holiday Inn\"}", MediaType.APPLICATION_JSON));
如果发现意外行为则测试失败,
例如 no further requests expected: HTTP 如果发送到意外的 URL
我的配置:
@SpringBootApplication(scanBasePackages = { "..." })
public class MyConfig extends SpringBootServletInitializer {
我的测试课
@ContextConfiguration( classes = {MyConfig.class})
@ActiveProfiles("local")
@WebAppConfiguration
public class My Test extends AbstractTestNGSpringContextTests {
@Autowired
@InjectMocks
private ServiceUnderMock serviceUnderMock;
private AutoCloseable closeable;
@BeforeClass
public void initMocks() {
closeable = MockitoAnnotations.openMocks(this);
mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
}
@AfterClass
public void releaseMocks() throws Exception {
closeable.close();
}
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
@Test
public void test() {
try {
mockServer.expect(ExpectedCount.min(1),
requestTo(new URI("https://www.google.com")))
.andExpect(method(HttpMethod.GET));
} catch (URISyntaxException e) {
Assert.fail("failed to create mock");
}
serviceUnderMock.doSomething();
}
那么为什么我们需要添加mockServer.verify()?
在测试结束时使用 verify() 来确保所有预期的请求都被实际执行。
【问题讨论】:
-
你能多加一点上下文吗?测试设置以及完整的异常/失败断言。
-
@rieckpil 添加了上下文
-
您在课堂上使用了哪些 Spring Boot 测试注释?现在这有点令人困惑,因为您首先声明您正在使用
mockServer.expect(requestTo("/hotels/42")),但随后在测试中您模拟了对 Google 的请求?你能澄清一下吗? -
@rieckpil 酒店来自文档链接,添加了类注释
标签: java spring spring-boot spring-test mockserver