【发布时间】:2016-09-16 11:29:59
【问题描述】:
我对发送 JAX-RS POST 调用的方法进行了 JUnit 测试。
为了独立于外部资源,我模拟了 REST 客户端并说应该返回一个虚拟响应。效果很好,没问题。但是:
当调用myResponse.readEntity(String.class) 时,我总是得到以下异常:
java.lang.IllegalStateException: RESTEASY003290: 实体不受输入流的支持
这是我的代码 sn-p 失败:
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class SimpleTest {
@Test
public void testReadResponse() {
final JsonObject responseContent = new JsonObject();
responseContent.add("field", new JsonPrimitive("This is a JSON for testing."));
final String expected = responseContent.toString();
final Response.ResponseBuilder builder = Response.ok()
.entity(responseContent.toString())
.header("Content-Type", MediaType.APPLICATION_JSON);
final Response dummyResponse = builder.build();
final String result = dummyResponse.readEntity(String.class); // <-- Exception is thrown here!
assertThat("JSON Strings are not identical.", result, is(expected));
}
}
和 Stacktrace:
java.lang.IllegalStateException: RESTEASY003290: Entity is not backed by an input stream
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:230)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:219)
at de.me.myproject.SimpleTest.testReadResponse(SimpleTest.java:43)
在调用未模拟的 REST API 的生产代码中,它返回自动构建响应,其中 .readEntity(String.class) 方法工作正常。
【问题讨论】:
标签: java rest junit mocking jax-rs