Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play framework - testing POST controller method

I wanted to test one of my POST methods in my controller, so I written something like this:

@Test
    public void shouldSaveNewCollectionToDatabase(){
        String body = "{\"name\":\"collectionName\", \"owner\": {}}";
        JsonNode json = Json.parse(body);
        FakeRequest request = new FakeRequest(POST, "/rest/collections/add").withJsonBody(json);

        Result result = callAction(controllers.routes.ref.SetsAndCollections.postCollection(), request);
        verify(questionSetCollectionDAO).save(any(QuestionSetCollection.class));
    }

the thing is, this test fails because controller method is not invoked at all so my questionSetCollectionDAO methods are not invoked.

I event put some printing at the top of the method:

@BodyParser.Of(Json.class)
@play.db.jpa.Transactional
public static Result postCollection(){
    System.out.println("I am here");
...

and I don't see any output on console.

If that is not the way I could invoke controller methods with fake requests, how can I do that?

I read about fakeApplication but I is there any other way to do some simple testing of POST controller methods?

like image 537
Andna Avatar asked Apr 21 '13 00:04

Andna


1 Answers

For testing your rest services, first of all you should start a fake application.

FakeApplication fakeApplication=fakeApplication();
start(fakeApplication);

And at end pf your Test it is recommanded to stop it

    stop(fakeApplication);

If you have many test methods you can add these methods in your Test Class to facilitate test process.

FakeApplication fakeApplication = fakeApplication();

@Before
public void beforeTest() {
    start(fakeApplication);
}

@After
public void afterTest() {
    stop(fakeApplication);
}
like image 188
Mohsen Kashi Avatar answered Sep 22 '22 11:09

Mohsen Kashi