4

我在 Play 2.6 上,使用 Java

我的控制器返回:

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

我想在测试中解析结果:

Result result = new MyController().xml();    
play.test.Helpers.contentAsString(result)

这抛出

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

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

4

2 回答 2

5

如异常消息所述,由于您的结果是流式实体,因此请使用该版本contentAsStringMaterializer. HelpersTest.java以下是 Play 存储库中使用该方法的示例:

@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"));
    }
}
于 2018-01-20T14:41:37.723 回答
1

从带有 akka 2.6 的 Play 2.8 开始,“ActorMaterializer”已被弃用。这是获得“Materializer”的方法

Materializer mat = Materializer.matFromSystem(actorSystem);

于 2020-04-02T12:06:47.900 回答