簡體   English   中英

如何使用JUnit和Mockito使用靜態util調用來測試Rest Controller

[英]How to test Rest Controller with static util invocation using JUnit and Mockito

我有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));
   ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM