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

我有带有方法create的Rest Controller(使用util类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)在测试中监视控制器:

@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));
   ...
上一篇:java-模拟的HttpServletResponse实例中的getContentType()返回为null


下一篇:java-春季测试-注入具有嵌套bean依赖项的模拟bean