我的控制器带有方法:
@PostMapping
@ResponseBody
public ResponseEntity<?> addPrivilege(@RequestBody PrivilegeDTO privilegeDTO)
{
Privilege result = privilegeRepository.save(new Privilege(0L, privilegeDTO.getName(), new HashSet<>()));
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(result.getId())
.toUri();
log.info(location.toString());
return ResponseEntity.created(location).build();
}
这是测试
def "AddPrivilege"()
{
given:
Map request = [id : 0,
name: "test_privilege"]
URL urlLocation = new URL("http://localhost:8080/api/privileges/0")
privilegeRepository.save(_) >> privilege
PrivilegeController privilegeController = new PrivilegeController(privilegeRepository)
mvc = MockMvcBuilders.standaloneSetup(privilegeController).build();
when:
def results = mvc.perform(
MockMvcRequestBuilders
.post("/api/privileges")
.contentType(MediaType.APPLICATION_JSON)
.content(toJson(request))
)
then:
results.andExpect(status().isCreated())
results.andExpect(header().string("Location", urlLocation.toString()))
}
运行测试时,响应中的“ Location”标头等于“ http://localhost/api/privileges/0”,但是当我使用Postman发送请求时,它是“ http://localhost:8080/api/privileges/0”。
我不明白为什么会有这样的差异。我可以以某种方式强制弹簧测试返回带有端口的URI吗?