【发布时间】:2020-12-29 21:38:06
【问题描述】:
我正在编写一个 Spring Boot Web 应用程序,并试图弄清楚如何对一种方法进行单元测试,该方法只是使用 junit 和 mockito 将记录保存到数据库,这是我以前从未使用过的。这是我的保存方法:
@PostMapping
public ResponseEntity<?> saveRecord(@RequestBody Record record, BindingResult result) {
if(!result.hasErrors()) {
Record newRecord = recordsService.save(record);
// Return the location of the created resource
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{recordId}").buildAndExpand(newRecord.getId()).toUri();
return new ResponseEntity<>(uri, HttpStatus.CREATED);
} else {
return new ResponseEntity<>(result.getAllErrors(), HttpStatus.BAD_REQUEST);
}
}
请注意,它返回一个 ResponseEntity> 对象,我有点不确定如何在测试中重新创建该对象,因为 ResponseEntity 可能包含 URI 或输入中的错误,以及 HttpStatus。所以我想知道是否可以在编写这个单元测试时获得一些帮助。假设我是从这个开始的:
@RunWith(MockitoJUnitRunner.class)
public class RecordsControllerTest {
@Mock
private RecordRepo recordRepo;
@InjectMocks
private RecordsService recordsService = new RecordsService();
@Test
public void saveRecordTest() {
Record mock = new Record();
//case 1: HttpStatus.CREATED
Mockito.when(recordsService.save(Mockito.any(Record.class))).thenReturn(...);
//case 2: HttpStatus.BAD_REQUEST
Mockito.when(recordsService.save(Mockito.any(Record.class))).thenReturn(...);
}
.
.
.
}
【问题讨论】:
-
我会一起推荐一种不同的方法:可以使用bean validation,而不是在 DTO 上使用
hasError()-方法。然后,当 bean 验证失败时,可以使用 exception mapper 将Exception映射到适当的 HTTP 响应。
标签: java spring-boot unit-testing junit mockito