【发布时间】:2022-01-17 03:20:46
【问题描述】:
我正在使用 JUnit 来测试应用程序的路由。问题是我正在向路由发出 PUT 请求,我认为它应该返回状态 200,但实际上它返回 404。我已经尝试过传递一个字符串并将 PathVariable 更改为字符串,使用 Long.parseLong( ) 但我仍然得到错误。我想知道为什么它返回 404 以及我做错了什么,当我的数据库中存在 ID 为 1 的 Persona 和 ID 为 1 的 Grupo 时。顺便说一句,我正在使用 JHipster 并且我正在 PersonaResourceIT 中进行这些测试已经定义了。非常感谢,代码如下:
角色资源:
@PutMapping("/personas/{id}/grupo/{idGrupo}")
public ResponseEntity<Void> vincularGrupo(@PathVariable Long id, @PathVariable Long idGrupo) {
log.debug("REST request to vincularGrupo : {}", id);
Optional<Persona> persona = personaRepository.findById(id);
if (persona.isPresent()) {
Persona persona2 = persona.get();
Optional<Grupo> grupo = grupoRepository.findById(idGrupo);
if (grupo.isPresent()) {
Grupo grupo2 = grupo.get();
persona2.setGrupo(grupo2);
personaRepository.save(persona2);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
} else {
return ResponseEntity.notFound().build();
}
}
PersonaResourceIT:
@Test
@Transactional
void asociarPersonaGrupoSuccess() throws Exception {
// Long id = (long) 1;
// Long idGrupo = (long) 1;
String id = "1";
String idGrupo = "1";
this.restPersonaMockMvc.perform(put("/api/personas/{id}/grupo/{idGrupo}", id, idGrupo))
.andExpect(status().isOk())
.andReturn();
}
我也尝试过使用 Long id = 1L 但它不起作用。我不断收到 404 状态。
【问题讨论】:
-
首先您必须确定数据库中缺少哪个实体,在调试器下应该很容易。然后,您应该查看创建这些实体的方式和时间,是在测试执行之前,在同一事务中,使用 liquibase 吗?
-
是的,它正在使用 Liquibase。问题是,在我的 application.yml 中,我没有表明我想使用 csv 文件进行集成测试,正如我向 geco17 指出的那样。非常感谢盖尔。每次我从 JHipster 那里学到新东西。
标签: java spring testing junit jhipster