javaplayframeworkakkaakka-streamplayframework-2.6

How can I get content from InputStream based results in Play tests


I am on Play 2.6, using Java

My controller returns:

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

I want to parse the result in tests:

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

This throws

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

How can I retrieve the content of results issued from input streams in tests?


Solution

  • As the exception message states, since your result is a streamed entity, use the version of contentAsString that takes a Materializer. Here's an example from HelpersTest.java in the Play repository that uses that method:

    @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"));
        }
    }