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

后端 未结 5 1964
梦谈多话
梦谈多话 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 12:57

    I used the same database engine that main database and dbunit for cleaning up before each test.

    public class SomeTest {
        // ...
    
        @Before
        public void startApp() throws Exception {
            // Set up connection to test database, different from main database. Config better should be used instead of hard-coding.
            Map settings = new HashMap();
            settings.put("db.default.url", "jdbc:mysql://localhost/somedatabase?characterEncoding=UTF-8&useOldAliasMetadataBehavior=true");
            settings.put("db.default.user", "root");
            settings.put("db.default.password", "root");
            settings.put("db.default.jndiName", "DefaultDS"); // make connection available to dbunit through JNDI
            app = Helpers.fakeApplication(settings);
            Helpers.start(app);
    
            databaseTester = new JndiDatabaseTester("DefaultDS");
    
            IDataSet initialDataSet = new FlatXmlDataSetBuilder().build(play.Play.application()
                    .resourceAsStream("/resources/dataset.xml"));
            databaseTester.setDataSet(initialDataSet);
            databaseTester.onSetup();
        }
    
        @After
        public void stopApp() throws Exception {
            databaseTester.onTearDown();
            Helpers.stop(app);
        }
    }
    

    My dataset.xml just contain table names to tell dbunit to empty these tables before each test. It also can contain fixtures.

    
    
      
      
    
    

    Evolutions run automatically on test database when using this approach, so if you remove all tables from test database, they will be recreated.

    It is overkill to use dbunit if you only need to clean tables, you can clean them by issuing query directly or by using ebean DdlGenerator. But I also use dbunit for comparing data.

    I don't use Helpers.running, because it takes Runnable and Runnable implementations cannot throw exceptions - very inconvenient for tests. But if you look at code for running(), it just calls Helpers.start() and Helpers.stop() so I call these methods directly in @Before and @After.

    Decided not to use H2 for running tests: yes, it runs faster, but there are too much difference between it and MySQL.

提交回复
热议问题