gpt4 book ai didi

java - org.springframework.web.bind.MethodArgumentNotValidException

转载 作者:行者123 更新时间:2023-12-02 11:02:09 27 4
gpt4 key购买 nike

我正在使用 spring boot,并且我有一个带有方法的 RestController

addBook(@Validated @RequestBody BookDto bookDto)

BookDto 有一个注释为只写的字段

@JsonProperty(access = Access.WRITE_ONLY)
@NotNull(message = "cannot be empty")
@Size(min = 1, max = 20)
private String isdnNo;

这按预期工作,我必须在发出发布请求时提供 isdnNo。当我得到它时,不要在响应中携带 isdnNo,这很好。这里的问题是在 JUnit 测试用例中。我正在使用独立设置来测试 Controller 。

MockMvcBuilders.standaloneSetup(bookController).build();
MockHttpServletRequestBuilder postRequest = MockMvcRequestBuilders.post("/books/").contentType(JSON)
.accept(JSON);
postRequest.content(asJsonString(bookDto));
ResultActions result = mvc.perform(postRequest);

这个 JUnit 测试用例给出了异常 org.springframework.web.bind.MethodArgumentNotValidException 并表示 idnNo 不能为空,即使我在执行 post 时在 bookDto 中提供了 isdnNo 。这里可能存在什么问题。

如果我删除@JsonProperty(access = Access.WRITE_ONLY)测试用例工作正常。

提前致谢!

最佳答案

您希望保留 Access.WRITE_ONLY 删除,因为根据文档,在序列化期间(即将其写入字符串),它不会读取序列化的值。您的方法 asJsonString 正在序列化对象,从而删除该值。

AUTO:
Access setting which means that visibility rules are to be used to automatically determine read- and/or write-access of this property.

READ_ONLY:
Access setting that means that the property may only be read for serialization, but not written (set) during deserialization.

READ_WRITE
Access setting that means that the property will be accessed for both serialization (writing out values as external representation) and deserialization (reading values from external representation), regardless of visibility rules.

WRITE_ONLY
Access setting that means that the property may only be written (set) for deserialization, but will not be read (get) on serialization, that is, the value of the property is not included in serialization.

https://fasterxml.github.io/jackson-annotations/javadoc/2.6/index.html?com/fasterxml/jackson/annotation/JsonProperty.Access.html

关于java - org.springframework.web.bind.MethodArgumentNotValidException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com