rom*_*the 5 java rest-assured objectmapper quarkus
我对 Quarkus 应用程序中的配置进行了非常简单的调整ObjectMapper,如 Quarkus 指南所述:
@Singleton
public class ObjectMapperConfig implements ObjectMapperCustomizer {
@Override
public void customize(ObjectMapper objectMapper) {
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
objectMapper.registerModule(new JavaTimeModule());
}
}
Run Code Online (Sandbox Code Playgroud)
我这样做是为了用@JsonRootName注释包装/解开我的对象:
@RegisterForReflection
@JsonRootName("article")
public class CreateArticleRequest {
private CreateArticleRequest(String title, String description, String body, List<String> tagList) {
this.title = title;
this.description = description;
this.body = body;
this.tagList = tagList;
}
private String title;
private String description;
private String body;
private List<String> tagList;
...
}
Run Code Online (Sandbox Code Playgroud)
当针对我的实际 API 时,这工作得很好curl,但是每当我在其中一个测试中使用 RestAssured 时,RestAssured 似乎不尊重我的 ObjectMapper 配置,并且不会按照注释所示的方式包装 CreateArticleRequest @JsonRootName。
@QuarkusTest
public class ArticleResourceTest {
@Test
public void testCreateArticle() {
given()
.when()
.body(CREATE_ARTICLE_REQUEST)
.contentType(ContentType.JSON)
.log().all()
.post("/api/articles")
.then()
.statusCode(201)
.body("", equalTo(""))
.body("article.title", equalTo(ARTICLE_TITLE))
.body("article.favorited", equalTo(ARTICLE_FAVORITE))
.body("article.body", equalTo(ARTICLE_BODY))
.body("article.favoritesCount", equalTo(ARTICLE_FAVORITE_COUNT))
.body("article.taglist", equalTo(ARTICLE_TAG_LIST));
}
}
Run Code Online (Sandbox Code Playgroud)
这将我的请求正文序列化为:
{
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "Very carefully.",
"tagList": [
"dragons",
"training"
]
}
Run Code Online (Sandbox Code Playgroud)
... 代替 ...
{
"article": {
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "Very carefully.",
"tagList": [
"dragons",
"training"
]
}
}
Run Code Online (Sandbox Code Playgroud)
我实际上可以通过手动配置 RestAssured ObjectMapper 来修复此问题,如下所示:
@QuarkusTest
public class ArticleResourceTest {
@BeforeEach
void setUp() {
RestAssured.config = RestAssuredConfig.config().objectMapperConfig(new ObjectMapperConfig().jackson2ObjectMapperFactory(
(cls, charset) -> {
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.registerModule(new JavaTimeModule());
return mapper;
}
));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我显然不想这样做!我希望 RestAssured 获取我的 ObjectMapper 配置,这样我就不需要保留两个不同的 ObjectMapper 配置。
为什么不被拾取?我缺少什么?
所以实际上 Quarkus 不会自动执行此操作(因为它会干扰本机测试)。
但是您可以使用:
@Inject
ObjectMapper
Run Code Online (Sandbox Code Playgroud)
在测试中进行设置RestAssured.config
| 归档时间: |
|
| 查看次数: |
1942 次 |
| 最近记录: |