How to mock controllers / rest endpoints for unit testing in Play Framework 2.x [Java]
Asked Answered
B

1

14

We are developing a project with Java on Play Framework 2.x and have some rest endpoints. Also we have some test cases for them like as follows:

    @Test
    public void testLogout() throws Exception {
        FakeRequest request = new FakeRequest("GET", "/product/api/v1/logout");

        Result result = route(request);

        assertThat(status(result)).isEqualTo(OK);
        assertThat(contentType(result)).isEqualTo("application/json");
        assertThat(contentAsString(result)).contains("result");
    }

On the other hand, we have some methods [like register()] which can not test in production database.

What is the correct way to test the methods which affect the prod database? I think mocking but I am not sure that and I don't know how to do. If mocking is a good choice, is there any working example?

Please give me some advice about this issue.

Bungalow answered 4/5, 2015 at 13:1 Comment(6)
have you checked out these links? playframework.com/documentation/2.3.4/JavaTest and playframework.com/documentation/2.3.4/JavaFunctionalTestPrussiate
Pact JVM seems to enable what you want to do, but maybe you should elaborate your question. It is derived from Pact for Ruby and "Enables consumer driven contract testing, providing a mock service and DSL for the consumer project, and interaction playback and verification for the service provider project."Monstrosity
@sfat: of course I checked out those links and I have lots of test. I just need mocking..Felicitous
@Pact JVM: thanks for advice. I'll check it out.Felicitous
What persistence framework do you use? Do you use DI?Penal
This project is a wrapper API project for an external API project. I don't know which framework(s) are using on other project or using DI.Felicitous
M
2

I think the correct way is not to test against production database.

I divide the tests in 2 groups, unit tests and integration tests. Unit tests are commonly known, and in integration tests I test everything that is outside the application itself (for example, the database) and the conections between them.

I run the unit tests using a mock in memory database when needed and integration tests against a database with same structure as the production one but not the same database.

I hope my approach will help you.

Mayda answered 5/5, 2015 at 9:27 Comment(1)
Thanks for your answer but I have no choice about testing prod database, this is company's choice (correct way or not..). I just want to know how to mock rest api methods (if possible).Felicitous

© 2022 - 2024 — McMap. All rights reserved.