gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:20 24 4
gpt4 key购买 nike

我有 Rest Controller,方法是 create(validation using 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 - 具有静态方法的实用程序类。它检查数据是否有效并且不执行任何操作或抛出带有状态代码(例如 404)的运行时异常。

如何在不删除验证的情况下修复它?

最佳答案

1) 将 validator 调用移至包级方法并进行小规模重构:

@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) 在测试中侦测 Controller :

@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 - 如何使用 JUnit 和 Mockito 通过静态 util 调用测试 Rest Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com