我对发送 JAX-RS POST
调用的方法进行了 JUnit 测试。
为了独立于外部资源,我 mock 了 REST 客户端并表示应该返回一个虚拟响应。效果很好,没问题。但是:
当调用 myResponse.readEntity(String.class)
时,我总是得到以下异常:
java.lang.IllegalStateException: RESTEASY003290: Entity is not backed by an input stream
这是我失败的代码片段:
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));
}
}
和堆栈跟踪:
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)
方法工作正常。
最佳答案
Response
是一个抽象类,RESTEasy 有不同的客户端和服务器子类,参见 BuiltResponse
和 ClientResponse
.并非每个子类都支持所有方法。
Response#readEntity
需要由输入流支持:
Method throws an
ProcessingException
if the content of the message cannot be mapped to an entity of the requested type andIllegalStateException
in case the entity is not backed by an input stream or if the original entity input stream has already been consumed withoutbuffering
the entity data prior consuming.
BuiltResponse
永远不会得到输入流的支持,因此您会得到一个 IllegalStateException
。
您可以使用 Response#getEntity
,它不需要输入流。
关于java - JAX-RS (Reasteasy) Response.readEntity 抛出 : IllegalStateException: RESTEASY003290: Entity is not backed by an input stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39530407/