我正在为我的控制器编写测试,我已经能够找到搜索端点了。我现在尝试了插入,但没有成功。
我的服务:
public LegalPerson insert(LegalPerson legalPerson) {
legalPerson.setId(null);
try {
legalPerson = repository.save(legalPerson);
} catch (DataIntegrityViolationException error) {
throw new DataIntegrity("Error something***", error);
}
return legalPerson;
}
public LegalPerson modelToEntity(LegalPersonModel personModel) {
return LegalPerson.builder()
.active(personModel.getActive())
.companyId(personModel.getCompanyId())
.tradeName(personModel.getTradeName())
.companyName(personModel.getCompanyName())
.email(personModel.getEmail())
.cnpj(personModel.getCnpj())
.stateRegistration(personModel.getStateRegistration())
.municipalRegistration(personModel.getMunicipalRegistration())
.openingDate(personModel.getOpeningDate())
.address(personModel.getAddress())
.companyType(personModel.getCompanyType())
.subsidiaries(personModel.getSubsidiaries())
.phones(personModel.getPhones())
.build();
}
我的休息控制器
@RestController
@RequestMapping(value = "/api/clients/lp")
public class LegalPersonResource {
/**other methods ***/
@PostMapping
public ResponseEntity<Void> insert(@Valid @RequestBody LegalPersonModel legalPersonModel) {
var legalPerson = service.modelToEntity(legalPersonModel);
legalPerson = service.insert(legalPerson);
return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(legalPerson.getId()).toUri()).build();
}
而我的测试
@Test
void insert() throws Exception {
var mockLPM = new LegalPersonModel(true, 1L, "mockTrade", "mockCompanyName", "mockTest@com", "63.236.885/0001-42", "123455", "1234566", localDate, 1L, CompanyEnum.HEADOFFICE,subsidiaries, phones);
var objason = new ObjectMapper();
objason.writeValueAsString(mockLPM);
var test = mvc.perform(MockMvcRequestBuilders.post("/api/clients/lp").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(String.valueOf(objason))).andReturn();
int status = test.getResponse().getStatus();
Assertions.assertEquals(201, status);
}
总是回归状态400.我做错了什么?
====更新:====
它部分工作。
它只适用于ObjectMapper,我必须将LocalDate更改为null,因为它会在一个巨大的字符串中对localDate进行修改:
"openingDate": {"year": 1955, "month": "OCTOBER", "monthValue": 10, "dayOfMonth": 25, "chronology": {"calendarType": "iso8601", "id" "}," era ":" CE "," dayOfYear ": 298," dayOfWeek ":" TUESDAY "," leapYear ": false}
实际上我的json应该是这样的:例如"openingDate": "2019-04-02"
。
因此,当我将localDate更改为null时,它会传递该部分,但在我的服务的那部分中出现NullPointerException:
var legalPerson = service.modelToEntity (legalPersonModel);
它识别legalPersonModel,这是我们刚刚使用ObjectMapper传递的内容,但legalPerson始终保持为null,它不会被转换。
我尝试了一些没有成功的事情。我该怎么办?
===更新2 ===
如果在其余控制器中,有:
return ResponseEntity.created (ServletUriComponentsBuilder.fromCurrentRequest (). path ("/ {id}")
.buildAndExpand (legalPerson.getId ()). toUri ()). build ();
将返回null。
但是,如果我切换到
return ResponseEntity.status (201) .build ();
我有一个绿色测试。
有什么方法可以解决这个问题吗?
只要你的400 Bad Request
ing有效载荷不是有效类型,你就会获得post
状态 - 在你的例子中,你应该post
一个可以反序列化为LegalPersonModel
对象的有效载荷。
您可以直接将有效负载发布为json
字符串
@Test
void insertAsJsonString() throws Exception {
var mockLPM = new LegalPersonModel(true,
1L,
"mockTrade",
"mockCompanyName",
"mockTest@com",
"63.236.885/0001-42",
"123455",
"1234566",
localDate,
1L,
CompanyEnum.HEADOFFICE,
subsidiaries,
phones);
var om = new ObjectMapper();
var test = mvc.perform(
MockMvcRequestBuilders
.post("/api/clients/lp")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(om.writeValueAsString(mockLPM))
.andReturn();
int status = test.getResponse().getStatus();
Assertions.assertEquals(201, status);
}
要将LocalDate
序列化为yyyy-MM-dd格式,请尝试像这样配置ObjectMapper
ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
您可能需要导入jackson-datatype-jsr310
。使用maven
导入它就像这样
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.8</version>
</dependency>
如果var legalPerson = service.modelToEntity (legalPersonModel);
总是导致legalPerson
是null
,即使LocalDate
被正确序列化,你还需要用LegalPerson
类更新问题,包括builder
模式。
我无法重现“更新2”问题。
鉴于此终点
@PostMapping
public ResponseEntity<Void> insert(@Valid @RequestBody LegalPersonModel legalPersonModel) {
var legalPerson = service.modelToEntity(legalPersonModel);
legalPerson = service.insert(legalPerson);
return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(legalPerson.getId()).toUri()).build();
}
将返回以下内容(使用命令行工具curl
)
$ curl -X POST -d @legalPersonModelMock 'http://localhost:8080/api/clients/lp'
< HTTP/1.1 201
< Location: http://localhost:8080/api/clients/lp/1
< Content-Length: 0
legalPersonModelMock
文件的内容是json
的var mockLPM = new LegalPersonModel(...)
表示。
你的service.insert(...)
代码设置legalPerson.setId(null);
,你确定没有弄乱响应吗?