[英]Mocking Save Method using JUnit/Mockito
I'm writing a spring boot web app and am trying to figure out how to unit test a method that is simply saving a record to a db using junit and mockito, which I've never used before. 这是我的保存方法:
@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<?> object,我有点不确定如何在测试中重新创建它,因为 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(...);
}
.
.
.
}
第一:如果你使用@InjectMocks,那么你不应该自己创建recordsService
,而是让 Mockito 创建它:
@InjectMocks
private RecordsService recordsService;
也就是说,我建议使用 @WebMvcTest 来测试 Spring 控制器。
@WebMvcTest(GreetingController.class)
public class RecordsControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private RecordsService 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(...);
}
.
.
.
}
有关更多详细信息,请参阅https://spring.io/guides/gs/testing-web/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.