Dav*_*nes 3 spring integration-testing spring-mvc spring-test spring-boot
我有一个Spring Boot应用程序,希望通过集成测试来覆盖我的REST控制器.这是我的控制器:
@RestController
@RequestMapping("/tools/port-scan")
public class PortScanController {
private final PortScanService service;
public PortScanController(final PortScanService portScanService) {
service = portScanService;
}
@GetMapping("")
public final PortScanInfo getInfo(
@RequestParam("address") final String address,
@RequestParam(name = "port") final int port)
throws InetAddressException, IOException {
return service.scanPort(address, port);
}
}
Run Code Online (Sandbox Code Playgroud)
在其中一个测试用例中,我想测试端点在某些情况下是否会抛出异常.这是我的测试类:
@RunWith(SpringRunner.class)
@WebMvcTest(PortScanController.class)
public class PortScanControllerIT {
@Autowired
private MockMvc mvc;
private static final String PORT_SCAN_URL = "/tools/port-scan";
@Test
public void testLocalAddress() throws Exception {
mvc.perform(get(PORT_SCAN_URL).param("address", "192.168.1.100").param("port", "53")).andExpect(status().isInternalServerError());
}
}
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?当前实现不处理从PortScanController.getInfo()抛出的InetAddressException,当我开始测试时,我收到并发生错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.handytools.webapi.exceptions.InetAddressException: Site local IP is not supported
Run Code Online (Sandbox Code Playgroud)
由于原始InetAddressException被NestedServletException包装,因此无法在@Test注释中指定预期的异常.
Spring Boot Test包附带AssertJ,它有非常方便的方法来验证抛出的异常.
验证原因:
@Test
public void shouldThrowException() {
assertThatThrownBy(() -> methodThrowingException()).hasCause(InetAddressException .class);
}
Run Code Online (Sandbox Code Playgroud)
您可能感兴趣的方法也很少.我建议您查看文档.
| 归档时间: |
|
| 查看次数: |
6046 次 |
| 最近记录: |