[英]Spring Boot rest controller test
I'm writing the tests for my controller and I've already been able to find the search endpoint. 我正在为控制器编写测试,并且已经可以找到搜索端点。 I tried the insert now, but without success.
我现在尝试插入,但是没有成功。
My Serivce : 我的服务:
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();
}
My rest controller 我的休息控制器
@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();
}
And my test 而我的测试
@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);
}
always returning status 400. What am I doing wrong? 总是返回状态400。我在做什么错?
==== UPDATE:==== ====更新:====
It worked in parts. 它部分起作用。
It worked only with the ObjectMapper, and I have to change LocalDate to null, as it tarnsforms the localDate in a huge string: 它仅与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}
And actually my json should look like this: "openingDate": "2019-04-02"
for example. 实际上,我的json应该如下所示:
"openingDate": "2019-04-02"
。
So when I change localDate by null, it passes that part, but a NullPointerException in that part of my service here: 因此,当我将nullDate更改为null时,它将传递该部分,但在此服务的该部分中将传递NullPointerException:
var legalPerson = service.modelToEntity (legalPersonModel);
it recognizes the legalPersonModel, which is what we just passed with the ObjectMapper, however the legalPerson always stays as null, it is not converted. 它可以识别legalPersonModel,这是我们刚刚与ObjectMapper一起传递的,但是legalPerson始终保持为空,不会进行转换。
I tried some things without success. 我尝试了一些没有成功的事情。 What should I do?
我该怎么办?
=== UPDATE 2 === ===更新2 ===
If in the rest controller, has: 如果在rest控制器中,则具有:
return ResponseEntity.created (ServletUriComponentsBuilder.fromCurrentRequest (). path ("/ {id}")
.buildAndExpand (legalPerson.getId ()). toUri ()). build ();
will return null. 将返回null。
But if I switch to 但是如果我切换到
return ResponseEntity.status (201) .build ();
I have a green test. 我有一个绿色测试。
Is there any way to solve this? 有什么办法解决这个问题?
You will get a 400 Bad Request
status whenever the payload you're post
ing is not a valid type - in your example you should post
a payload that can be deserialized into a LegalPersonModel
object. 每当您
post
的有效负载不是有效类型时,您将获得400 Bad Request
状态-在您的示例中,您应该post
可以反序列化为LegalPersonModel
对象的有效负载。
You can either post the payload directly as a json
string 您可以将有效载荷直接作为
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);
}
To serialize LocalDate
into yyyy-MM-dd format, try configuring the ObjectMapper
like this 要将
LocalDate
序列化为yyyy-MM-dd格式,请尝试像这样配置ObjectMapper
ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
You might need to import the jackson-datatype-jsr310
. 您可能需要导入
jackson-datatype-jsr310
。 Using maven
import it like so 使用
maven
像这样导入
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.8</version>
</dependency>
If the var legalPerson = service.modelToEntity (legalPersonModel);
如果
var legalPerson = service.modelToEntity (legalPersonModel);
always results in legalPerson
being null
even if the LocalDate
is serialized correctly you'll need to update the question with the LegalPerson
class including the builder
pattern. 即使
LocalDate
已正确序列化,也始终会导致legalPerson
为null
,您将需要使用LegalPerson
类(包括builder
模式)更新问题。
I am unable to reproduce the "Update 2" problem. 我无法重现“更新2”问题。
Given this end point 给定这个终点
@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();
}
Will return the following (using the command line tool curl
) 将返回以下内容(使用命令行工具
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
Content of the legalPersonModelMock
file is an json
representation of var mockLPM = new LegalPersonModel(...)
. legalPersonModelMock
文件的内容是var mockLPM = new LegalPersonModel(...)
的json
表示形式。
Your code for service.insert(...)
sets legalPerson.setId(null);
您的
service.insert(...)
代码设置为legalPerson.setId(null);
, are you sure that's not messing with the response? ,您确定不会弄乱响应吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.