Reputation: 6689
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?
Upvotes: 6
Views: 3929
Reputation: 4596
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);
}
Upvotes: 2
Reputation: 1528
Can you print out the http status code of your results? If it is a 303 redirect - which it sounds like it is (since the controller is not getting called), it is most likely that you need to provide a login play-session cookie to execute the POST method.
See this answer on how to get an auth cookie in Play 2: https://stackoverflow.com/a/13953375/286550
Upvotes: 0