【发布时间】:2021-07-08 00:18:32
【问题描述】:
使用 Quarkus,我有以下 API。
@RequestScoped
@Path("/api/v1")
public class MyApi {
@POST
@Consumes(APPLICATION_JSON)
public Response create(Entity entityToCreate) {
if (entityToCreate.isValid()) {
// create the entity in my app...
return Response.ok().build();
} else {
return Response.status(BAD_REQUEST).build();
}
}
}
我的Entity 班级看起来像这样
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Entity {
private final String property1;
private final String property2;
// ...
@JsonCreator
public Entity(@JsonProperty("property1") String property1,
@JsonProperty("property2") String property2,
// ...
){
this.property1 = property1;
this.property2 = property2;
// ...
}
// getters for every property...
public boolean isValid() {
// check if the entity is valid, then return true or false
}
}
在我的单元测试中,我想要实现的目标如下:
import static io.restassured.RestAssured.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@QuarkusTest
public class MyApiTest {
private final Entity entityMock = mock(Entity.class);
@Test
public void shouldCreateEntityWhenValid(){
when(entityMock.isValid()).thenReturn(true);
given()
.contentType(ContentType.JSON)
.body(entityMock)
.when()
.post("/api/v1")
.then()
.statusCode(200);
}
@Test
public void shouldNotCreateEntityWhenInvalid(){
when(entityMock.isValid()).thenReturn(false);
given()
.contentType(ContentType.JSON)
.body(entityMock)
.when()
.post("/api/v1")
.then()
.statusCode(400);
}
}
目前,我遇到以下错误,因为杰克逊试图反序列化模拟。
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.mockito.internal.invocation.mockref.MockWeakReference and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: blah blah blah... )
【问题讨论】:
标签: java mockito junit5 rest-assured quarkus