我已经对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());
}
}
我这样做是为了用@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;
...
}
[在针对我的实际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));
}
}
这将我的请求正文序列化为:
{
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "Very carefully.",
"tagList": [
"dragons",
"training"
]
}
...代替...
{
"article": {
"title": "How to train your dragon",
"description": "Ever wonder how?",
"body": "Very carefully.",
"tagList": [
"dragons",
"training"
]
}
}
我实际上可以通过手动配置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;
}
));
}
}
但是,我显然不想这样做!我希望RestAssured选择我的ObjectMapper配置,这样我就不需要保留两个不同的ObjectMapper配置。
为什么不捡起它?我想念什么?
因此,实际上Quarkus不会自动执行此操作(因为它会干扰本机测试)。>>
但是您可以使用:
@Inject ObjectMapper
在测试中以设置
RestAssured.config