How to create unit tests against non in-memory database such as MySQL in Play framework, with resetting to known state?

后端 未结 5 1965
梦谈多话
梦谈多话 2020-12-23 12:34

I want to create unit tests that cover code that use relational database in Play framework 2.1.0. There are many possibilities for this and all cause problems:

Test

5条回答
  •  天命终不由人
    2020-12-23 13:03

    First, I would recommend you to use the same RDBMS for testing and production as it could avoid some hard-to-find bugs.

    Concerning the need to clean your database between each test, you can use Ebean DdlGenerator to generate scripts to create a clean database and JUnit's @Before annotation to automatically execute these scripts before every test.

    Using the DdlGenerator can be done like this :

        EbeanServer server = Ebean.getServer(serverName);
        ServerConfig config = new ServerConfig();
        DdlGenerator ddl = new DdlGenerator((SpiEbeanServer) server, new MySqlPlatform(), config);
    

    This code can be placed in a base-class that you could make inherit your tests (or inside a custom Runner that you can use with the @RunWith annotation).

    It will also allow you to easily automate the FakeApplication creation, avoiding some boilerplate code.

    Some links that can be helpful :

    • http://blog.matthieuguillermin.fr/2012/03/unit-testing-tricks-for-play-2-0-and-ebean/
    • https://gist.github.com/nboire/2819920

提交回复
热议问题