如何在 Play 测试中从基于 InputStream 的结果中获取内容

apf*_*ger 4 java akka playframework akka-stream playframework-2.6

我在 Play 2.6,使用 Java

我的控制器返回:

public Result xml() {
    return Results.ok(new ByteArrayInputStream("<someXml />".getBytes()));
}
Run Code Online (Sandbox Code Playgroud)

我想在测试中解析结果:

Result result = new MyController().xml();    
play.test.Helpers.contentAsString(result)
Run Code Online (Sandbox Code Playgroud)

这抛出

failed: java.lang.UnsupportedOperationException: Tried to extract body from a non strict HTTP entity without a materializer, use the version of this method that accepts a materializer instead
Run Code Online (Sandbox Code Playgroud)

如何在测试中检索从输入流发出的结果的内容?

Jef*_*ung 5

正如异常消息所述,由于您的结果是流式实体,因此请使用contentAsString带有Materializer. 以下是HelpersTest.javaPlay 存储库中使用该方法的示例:

@Test
public void shouldExtractContentAsStringFromAResultUsingAMaterializer() throws Exception {
    ActorSystem actorSystem = ActorSystem.create("TestSystem");

    try {
        Materializer mat = ActorMaterializer.create(actorSystem);

        Result result = Results.ok("Test content");
        String contentAsString = Helpers.contentAsString(result, mat);
        assertThat(contentAsString, equalTo("Test content"));
    } finally {
        Future<Terminated> future = actorSystem.terminate();
        Await.result(future, Duration.create("5s"));
    }
}
Run Code Online (Sandbox Code Playgroud)