简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM