Play framework - test method of the POST controller

I wanted to test one of my POST methods in my controller, so I wrote 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 fact is that this test fails because the controller method is not called at all, so my questionSetCollectionDAO methods are not called.

Event

I puts some print at the beginning of the method:

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

and I do not see the console output.

If this is not the case, how can I call controller methods with fake requests, how can I do this?

I read about fakeApplication , but do I have any other way to do simple testing of the POST controller methods?

+6
source share
2 answers

To test your vacation services, first of all, you must start a fake application.

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

And at the end of your test it is recommended to stop it

  stop(fakeApplication); 

If you have many testing methods, you can add these methods to your test class to facilitate the testing process.

 FakeApplication fakeApplication = fakeApplication(); @Before public void beforeTest() { start(fakeApplication); } @After public void afterTest() { stop(fakeApplication); } 
+2
source

Can you print the http status code of your results? If this redirect is 303, it looks like it is (since the controller is not called), most likely you need to provide a cookie to the login session in order to execute the POST method.

See this answer on how to get an auth cookie in Play 2: fooobar.com/questions/302110 / ...

0
source

All Articles