Alain
Alain

Reputation: 385

PlayFramework - Running functional test with json rendering

I'm trying to run this functional test

    public class JsonRenderTest extends FunctionalTest {    
        @Before
        public void setup() {
            Fixtures.deleteDatabase();
            Fixtures.loadModels("data.yml");
        }

        @Test
        public void testThatJsonRenderingWorks() {
            Response response = GET("/recipe/1");
            assertIsOk(response);
        }
     }

The action answering this call is this

    public static void showRecipe(Long id){
        Recipe recipe = Recipe.findById(id);
        notFoundIfNull(recipe);
        renderJSON(recipe);
    }

When I run the test in firefox using the TestRunner at http://localhost:8080/@tests I get this error message:

Failure, Response status expected:<200> but was:<404>

Now if I run this url http://localhost:8080/recipe/1 in a browser, I get the json responce I'm expecting wich is a json representation of my recipe object.

There is of course a recipe in the database with id 1.

Now here is my question. Why is the test failing when the browser is not. I tryed this in Chrome, IE and FF with the same result.

Any pointers would be much appreciated. Thanks

-Alain

Upvotes: 2

Views: 477

Answers (2)

Alain
Alain

Reputation: 385

Thanks eveyone. Ok I found the answer. It appears that my test was running before the fixture data was fully loaded. I was running my tests against a local MySql database. When I removed the call

Fixtures.deleteDatabase();

The test was running fine.

To fix the problem I am now running my test against a mem database with this in the application.conf file

%test.db.url=jdbc:h2:mem:play;MODE=MYSQL;LOCK_MODE=0

Upvotes: 1

Seb Cesbron
Seb Cesbron

Reputation: 3833

You can use a helper method to add content type to your request

public Request jsonRequest(Request request) {
    request.contentType = "application/json";
    request.format = "json";
    return request;

}

Then your test become

    @Test
    public void testThatJsonRenderingWorks() {
        Response response = GET(jsonRequest(newRequest)), "/recipe/1");
        assertIsOk(response);
    }
 }

You can also you WS classes to do real http tests insted.

Upvotes: 0

Related Questions