我正在尝试为以下控制器编写 Junit 测试:
@Value("${custom.properties.list}")
private List<String> stringList;
final DataService dataService;
@PostMapping("/")
public ResponseEntity<?> createValue(
@Valid @RequestBody final ObjectDto dto,
@RequestHeader(value = "headerField") final String headerValue) {
if (this.stringList.stream().noneMatch(headerValue::startsWith)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("error 403");
}
Long idResult = this.dataService.create(dto, headerValue);
if (Objects.equals(idResult, -1L)) {
return ResponseEntity.status(HttpStatus.204).body("error 204");
}
return new ResponseEntity<>(idResult, HttpStatus.CREATED);
}
假设
stringList
包含值 "ABC", "EFG", "HIJ"
。
我正在测试 headerValue
以列表中的值之一开头,以返回代码 201 或 204。
我的 Junit 测试如下:
@Test
void testCreateValue_1() throws Exception {
String requestBody = new String(Files.readAllBytes(Paths.get("src/test/resources/post/postRequest_1.json")));
MyObjectData data = mapper.readValue(requestBody, MyObjectData.class);
Mockito.when(dataService.create(data, "ABC")).thenReturn(1L);
mvc.perform(post("/")
.header("Nom-Application", "ABC")
.content(requestBody)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isCreated());
}
我不确定为什么,因为我对 Junit 测试还很陌生,但运行测试失败会返回代码 403。 我尝试在控制器测试类中创建列表,就像我在控制器类中所做的那样,但它不起作用。
我应该怎么做才能让我的测试通过并返回代码 201 ?
编辑:或者也许与从属性文件获取我的 stringList 有关?
编辑2:我意识到当我启动测试时
stringList
中的唯一值是"${custom.properties.list}"
,所以我之前编辑的答案是“是”。有什么方法可以在我的测试类中更新该值吗?
我所要做的就是在我的测试文件中创建一个 test.properties (确保路径与 /src/main 目录中的路径相同),并使用以下注释标记我的测试类
@TestPropertySource(locations = "classpath:test.properties")
。
此注释意味着 test.properties
将覆盖主目录中的属性文件。问题解决了,我的所有测试都成功了。