【发布时间】:2021-12-13 16:04:20
【问题描述】:
我正在使用Spring Boot 2.5.6 和JUnit 4.13.2。我的任务是测试DELETE方法
我的 REST 控制器:
@RestController
public class DomainEndpoint {
private final SomeService service;
@DeleteMapping("/domain/{id}")
public void delete(@PathVariable long id) {
service.delete(id);
}
}
我的测试:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class DomainEndpointTest {
@Autowired
TestRestTemplate template;
@MockBean
SomeService service;
@Test
public void delete() {
String url = "/domain/123";
ResponseEntity<?> resp = template.exchange(url, HttpMethod.DELETE, new HttpEntity<>(""), String.class);
assertEquals(HttpStatus.NO_CONTENT, resp.getStatusCode());
}
}
如您所见,我发现的测试“DELETE”方法的唯一解决方案是:
ResponseEntity<?> resp = template.exchange(url, HttpMethod.DELETE, new HttpEntity<>(""), String.class);
但是身体 new HttpEntity<>("") 和返回类型 String.class 的参数对我来说似乎很奇怪。我为什么要使用它们?我可以在不传递不必要参数的情况下更直接地做同样的事情吗?
另一方面,TestRestTemplate template 有一组简短易读的方法delete()。他们的问题 - 他们返回void,在这种情况下我无法检查响应状态代码。
主要问题是如何正确测试DELETE方法?
【问题讨论】:
标签: java spring spring-boot rest junit