【问题标题】:Mocking Save Method using JUnit/Mockito使用 JUnit/Mockito 模拟保存方法
【发布时间】: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


【解决方案1】:

首先:如果你使用@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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    相关资源
    最近更新 更多