我正在为控制器编写测试,并且已经能够找到搜索端点。我现在尝试插入,但是没有成功。
我的秘密:
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始终保持为空,不会进行转换。
我尝试了一些没有成功的事情。我该怎么办?
===更新2 ===
如果在rest控制器中,则具有:
return ResponseEntity.created (ServletUriComponentsBuilder.fromCurrentRequest (). path ("/ {id}")
.buildAndExpand (legalPerson.getId ()). toUri ()). build ();
将返回null。
但是如果我切换到
return ResponseEntity.status (201) .build ();
我有一个绿色测试。
有什么办法解决这个问题?
答案 0 :(得分:1)
每当400 Bad Request
的有效负载不是有效类型时,您都会获得post
状态-在您的示例中,您应该post
可以反序列化为{ {1}}个对象。
您可以直接将有效载荷作为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);
}
序列化为yyyy-MM-dd格式,请尝试像这样配置LocalDate
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
模式。
我无法重现“更新2”问题。
给出此终点
builder
将返回以下内容(使用命令行工具@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
的{{1}}表示形式。
您为json
设置了var mockLPM = new LegalPersonModel(...)
的代码,您确定它不会弄乱响应吗?