Chapter 13

Testing your mappers

Mocking a mapper proves nothing: the interface has no logic. The value is entirely in the SQL, so the only useful test runs it against a database.

⏱ 18 min readLevel: intermediateJUnit 5
What to test where

Mock the mapper when testing a service's branching logic. Never mock it when the thing under test is the query. A mapper test that stubs findById to return a fixed user has verified that Mockito works.

Three levels, three costs

LevelRuns againstSpeedCatches
Mapper unit testH2 in memory~50 msTypos, mapping errors, dynamic SQL branches
Mapper integration testTestcontainers, real engine~2 s (shared container)Dialect issues, index behaviour, constraint names
Service/slice testSpring context + DB~5 sTransaction boundaries, rollback rules

Plain JUnit 5 with H2

No Spring, no container — the fastest possible feedback loop for mapper work.

src/test/resources/mybatis-config-test.xml
<configuration>
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="logImpl" value="SLF4J"/>
  </settings>

  <typeAliases><package name="com.bitsnippets.shop.domain"/></typeAliases>

  <environments default="test">
    <environment id="test">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="org.h2.Driver"/>
        <property name="url"    value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>

  <mappers><package name="com.bitsnippets.shop.mapper"/></mappers>
</configuration>
UserMapperTest.java
package com.bitsnippets.shop.mapper;

import com.bitsnippets.shop.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.*;
import org.junit.jupiter.api.*;

import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class UserMapperTest {

    private static SqlSessionFactory factory;

    private SqlSession session;
    private UserMapper mapper;

    @BeforeAll
    static void buildFactory() throws Exception {
        try (InputStream in = Resources.getResourceAsStream("mybatis-config-test.xml")) {
            factory = new SqlSessionFactoryBuilder().build(in);
        }
    }

    @BeforeEach
    void openSessionAndSeed() throws Exception {
        session = factory.openSession();
        mapper  = session.getMapper(UserMapper.class);

        Connection connection = session.getConnection();
        ScriptRunner runner = new ScriptRunner(connection);
        runner.setLogWriter(null);
        try (Reader schema = Resources.getResourceAsReader("schema.sql");
             Reader data   = Resources.getResourceAsReader("data.sql")) {
            runner.runScript(schema);
            runner.runScript(data);
        }
    }

    @AfterEach
    void rollbackAndClose() {
        session.rollback();   // every test starts from the same state
        session.close();
    }

    @Test
    @DisplayName("findById maps every column, including snake_case ones")
    void findById() {
        User user = mapper.findById(1L).orElseThrow();

        assertAll(
            () -> assertEquals(1L, user.getId()),
            () -> assertEquals("jerin", user.getUserName()),
            () -> assertEquals("jerin@example.com", user.getEmail()),
            () -> assertNotNull(user.getCreatedAt(), "created_at must be mapped")
        );
    }

    @Test
    void findByIdReturnsEmptyForUnknownId() {
        assertTrue(mapper.findById(99_999L).isEmpty());
    }

    @Test
    void insertPopulatesGeneratedKey() {
        User user = new User();
        user.setUserName("neha");
        user.setEmail("neha@example.com");
        user.setStatus("ACTIVE");

        assertEquals(1, mapper.insert(user));
        assertNotNull(user.getId(), "generated key must be written back");
    }

    @Test
    void optimisticUpdateFailsOnStaleVersion() {
        User user = mapper.findById(1L).orElseThrow();
        user.setEmail("first@example.com");
        assertEquals(1, mapper.update(user));

        user.setEmail("second@example.com");   // version is now stale
        assertEquals(0, mapper.update(user));
    }
}

Covering every dynamic SQL branch

A search mapper with five optional filters has thirty-two paths. Parameterised tests keep that honest without thirty-two methods.

UserSearchTest.java
@ParameterizedTest(name = "name={0} status={1} expected={2}")
@CsvSource({
    "null,   null,       4",
    "je,     null,       1",
    "null,   ACTIVE,     3",
    "je,     ACTIVE,     1",
    "zzz,    null,       0",
    "null,   SUSPENDED,  1"
})
void searchHonoursEveryFilterCombination(String name, String status, int expected) {

    UserQuery query = new UserQuery();
    query.setNameLike("null".equals(name)   ? null : name);
    query.setStatuses("null".equals(status) ? null : List.of(status));

    assertEquals(expected, mapper.search(query).size());
}

@Test
void emptyIdListIsRejectedBeforeReachingTheDatabase() {
    assertEquals(0, userService.deleteAll(List.of()));
}

The @MybatisTest slice

mybatis-spring-boot-starter-test provides a slice that loads only the data-access layer: the data source, the SqlSessionFactory and your mappers. Each test method runs in a transaction that is rolled back afterwards.

pom.xml
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter-test</artifactId>
  <version>3.0.3</version>
  <scope>test</scope>
</dependency>
UserMapperSliceTest.java
@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Sql(scripts = {"/schema.sql", "/data.sql"})
class UserMapperSliceTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    void findsSeededUsers() {
        assertEquals(3, userMapper.findAll().size());
    }

    @Test
    void insertIsRolledBackAfterTheTest() {
        User user = new User();
        user.setUserName("temp");
        user.setEmail("temp@example.com");
        user.setStatus("ACTIVE");

        userMapper.insert(user);
        assertEquals(4, userMapper.findAll().size());
        // rolled back automatically — the next test still sees 3
    }
}

Testcontainers: the tests that count

H2 is not PostgreSQL. It has different reserved words, different JSONB support, different upsert syntax and different error codes. Anything vendor-specific must be tested on the real engine.

pom.xml
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>postgresql</artifactId>
  <version>1.19.8</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>junit-jupiter</artifactId>
  <version>1.19.8</version>
  <scope>test</scope>
</dependency>
AbstractPostgresTest.java
@SpringBootTest
@Testcontainers
public abstract class AbstractPostgresTest {

    // static: one container shared by every subclass, started once per JVM
    @Container
    static final PostgreSQLContainer<?> POSTGRES =
            new PostgreSQLContainer<>("postgres:16-alpine")
                    .withDatabaseName("shop")
                    .withUsername("shop_app")
                    .withPassword("test")
                    .withReuse(true);

    @DynamicPropertySource
    static void datasourceProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url",      POSTGRES::getJdbcUrl);
        registry.add("spring.datasource.username", POSTGRES::getUsername);
        registry.add("spring.datasource.password", POSTGRES::getPassword);
    }
}
OrderMapperIT.java
@Sql(scripts = {"/schema.sql", "/data.sql"},
     executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Transactional
class OrderMapperIT extends AbstractPostgresTest {

    @Autowired
    private OrderMapper orderMapper;

    @Test
    void upsertUsesOnConflictOnPostgres() {
        Order order = newOrder("ORD-1", new BigDecimal("120.00"));

        orderMapper.upsert(order);
        order.setTotal(new BigDecimal("150.00"));
        orderMapper.upsert(order);

        assertEquals(new BigDecimal("150.00"),
                     orderMapper.findByReference("ORD-1").getTotal());
        assertEquals(1, orderMapper.countByReference("ORD-1"));
    }

    @Test
    void jsonbAttributesRoundTrip() {
        Product product = new Product();
        product.setSku("SKU-9");
        product.setName("Desk lamp");
        product.setAttributes(Map.of("colour", "black", "watts", 9));

        productMapper.insert(product);

        Product loaded = productMapper.findById(product.getId());
        assertEquals("black", loaded.getAttributes().get("colour"));
    }
}
Keep the container warm

A static container plus withReuse(true) (and testcontainers.reuse.enable=true in ~/.testcontainers.properties) means one startup for the whole suite instead of one per class. That is usually the difference between a two-minute build and a twenty-minute one.

Asserting the SQL that actually ran

To catch N+1 regressions, count statements. A tiny interceptor registered only in tests does the job.

StatementCounter.java (test scope)
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class}))
public class StatementCounter implements Interceptor {

    private final AtomicInteger count = new AtomicInteger();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        count.incrementAndGet();
        return invocation.proceed();
    }

    public void reset()   { count.set(0); }
    public int  count()   { return count.get(); }
}
NoNPlusOneTest.java
@Test
void listEndpointIssuesExactlyOneQuery() {
    counter.reset();

    List<User> users = userMapper.findAllWithOrders();

    assertEquals(50, users.size());
    assertEquals(1, counter.count(),
            "findAllWithOrders must use a join, not a nested select");
}

Fixture strategy

ApproachGoodBad
SQL scripts (@Sql)Explicit, fast, readable diffsDrifts from the schema unless it is the same migration
Object mothers / buildersType-safe, refactor-friendlyNeeds working insert mappers first
Flyway migrations in testsGuarantees the schema matches productionSlower startup
Shared seed + per-test rollbackFast and isolatedHides ordering bugs if a test commits
Run the real migrations

If production is migrated by Flyway, tests should be too. A separate hand-written schema.sql will diverge, and the day it does you will get a green build and a failed deployment.

Checklist

  • Every mapper method has at least one test that executes it.
  • Every dynamic branch is exercised, including the all-null case.
  • Nested mappings assert the child collection size, not just the parent.
  • Vendor-specific SQL is tested on the real engine.
  • List endpoints assert a query-count upper bound.
  • Optimistic locking has a failing-path test.

Your ON CONFLICT upsert passes on H2 and fails in production on PostgreSQL 16. What is the most likely cause?

H2 emulates other dialects loosely. Conflict targets, partial indexes and JSONB operators are common divergence points. Anything vendor-specific belongs in a Testcontainers test against the actual engine and version you deploy.