Using H2 in Spring Tests

April 1, 2020

Rather then mock out my database layer code I decided to use the H2 in memory database to effectively provide a mock database implementation, where SQL would work as expected.

For unit tests, this can be done using an annotation:

package com.drumcoder.diary.test.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "spring.config.name=store-tests-h2",
                   "spring.datasource.url=jdbc:h2:mem:db-store-tests;DB_CLOSE_DELAY=-1;MODE=MSSQLServer" })
@ActiveProfiles("test")
public class StoreTests {
    @Autowired
    private StoreService storeService;

    @Test
    public void testNameRequired() {
        try {
            final Store store = new Store("");
            this.storeService.create(store);
            fail("Name of a store is a required field");
        } catch (final Exception ex) {
            // Exception expected
        }
}

Tags: junit h2 test unit