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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With