Skip to content

Unit Test

Kazuki Shimizu edited this page Jan 20, 2019 · 2 revisions

We appreciate that users fill issues with bug reports, feature suggestions or new ideas. This is in fact the basis of the evoution of MyBatis.

To facilitate the adoption of your idea or to demonstrate a failure we would like to ask you to provide unit tests. A test will make life easier for everyone, it will be easier for you to explain the idea or problem and for team members to understand it and take an action.

Before continue reading, please read our contribution guide!

Base Unit Test

Even if you are not familiar with unit testing you will see that coding a unit test is an easy task.
MyBatis provides a sample base test that serves as a basis for your test. The files for the base test are found in the following directory:
src/test/java/org/apache/ibatis/submitted/basetest
This test is quite simple, it is composed by the following files:

  • A JUnit test program called BaseTest
  • A POJO called User
  • A Mapper interface called Mapper
  • A mybatis-config file called mybatis-config.xml
  • A mapper XML file called Mapper.xml
  • A database script called CreateDB.sql

This is how it works.

BaseTest.setUp() method builds an SqlSessionFactory that uses an in-memory HSQLDB database:

try (Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/basetest/mybatis-config.xml")) {
  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}

Then it populates the database with the content of CreateDB.sql file:

BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(),
        "org/apache/ibatis/submitted/basetest/CreateDB.sql");

BaseTest.shouldGetAUser() gets a mapper and uses it to retrieve a User. Then it calls JUnit's method assertEquals to check that the returned data is what was expected:

@Test
void shouldGetAUser() {
  try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    User user = mapper.getUser(1);
    Assertions.assertEquals("User1", user.getName());
  }
}

Code your own Test

Taking base test as a basis these are the modifications you should do to build your own test:

  • Change package name from org.apache.ibatis.submitted.basetest to org.apache.ibatis.submitted.xxx where xxx is your test name
  • Note that you should also change String literals that hold the package in BaseTest#setUp (twice), in mybatis-config and in Mapper.xml.
  • Change database name both in BaseTest and mybatis-config.xml from jdbc:hsqldb:mem:basetest to jdbc:hsqldb:mem:xxx where xxx is your test name.
  • Run the test. It should finish OK.
  • Add your own code.
  • Once you are done, commit and push your changes (including the tests) to your fork and send us a pull request.

Please read the code contribution guide for the workflow details.

Clone this wiki locally