当前位置: 代码迷 >> java >> 如何使用JUnit和Mockito使用静态util调用来测试Rest Controller
  详细解决方案

如何使用JUnit和Mockito使用静态util调用来测试Rest Controller

热度:82   发布时间:2023-07-17 20:28:32.0

我有Rest控制器的方法create( 使用util class + databaseService 验证 (databaseDao + caching))

@RestController
@RequestMapping("files")
public class FilesController {
    private IDbFilesDao dbFilesService;
    private Map<String, Table> tables;

    public FilesController(IDbFilesDao dbFilesService, Map<String, Table> tables) {
        this.dbFilesService = dbFilesService;
        this.tables = tables;
    }

    @PostMapping("{table}")
    public ResponseEntity createTable(@PathVariable("table") String tableName,
                                         @RequestBody File file) {
        FilesValidator.validateAdding(tableName, tables, file);

        dbFilesService.create(tableName, file);

        URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(file.getKey()).toUri();
        return ResponseEntity.created(location).build();
    }
}

我有一个测试:

@RunWith(SpringRunner.class)
@WebMvcTest(value = FilesController.class, secure = false)
public class FilesControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private IDbFilesDao dbFilesService;

    @MockBean
    private Map<String, Table> tables;

    @Test
    public void create() throws Exception {
        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post("/files/tableName")
                .accept(MediaType.APPLICATION_JSON)
                .content(POST_JSON_BODY)
                .contentType(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = result.getResponse();
        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
    }
}

它只在@RestContoller中没有这一行时效果很好:

FilesValidator.validateAdding(tableName, tables, file);

有了这一行 - 找不到404。

FilesValidator - 带有静态方法的util类。 它检查数据是否有效并且什么都不做,或者使用状态代码(例如404)抛出运行时异常。

如何在不退出验证的情况下修复它?

1)将验证器调用移动到包级别方法并进行小型重构:

@PostMapping("{table}")
    public ResponseEntity createTable(@PathVariable("table") String tableName,
                                         @RequestBody File file) {
        validateAdding(tableName, tables, file);
        ...
}

validateAdding(String tableName, Map<String, Table> tables, File file){
    FilesValidator.validateAdding(tableName, tables, file);
}

2)在测试中窥探控制器:

@SpyBean
private FilesController filesControllerSpy;

3)使validateAdding方法不执行任何操作:

@Test
public void create() throws Exception {

   doNothing().when(filesControllerSpy)
     .validateAdding(any(String.class), any(Map.class), any(File.class));
   ...
  相关解决方案