如何使用JUNIT和MOCKITO使用静态使用调用来测试REST控制器



我的rest控制器具有create(使用util class databaseservice 的验证(databasedao 缓存))

@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) SPY测试中的控制器:

@SpyBean
private FilesController filesControllerSpy;

3) make validateAdding方法什么都不做:

@Test
public void create() throws Exception {
   doNothing().when(filesControllerSpy)
     .validateAdding(any(String.class), any(Map.class), any(File.class));
   ...

相关内容

  • 没有找到相关文章

最新更新