1

Is it possible to set up a Spring @DataJpaTest that uses liquibase with a temporary MySQL (so we can use the MySQL specific functions and syntax).

I was thinking that to do this, I'd have to use testcontainers to create a temporary MySQL instance for the test and somehow configure DataJpaTest to use the embedded one.

@RunWith(SpringRunner.class)
@ContextConfiguration(
    classes = {
        BlankJpaTest.class
    }
)
@EnableJpaRepositories(
    basePackageClasses = {
        Organizations.class
    }
)
@EntityScan(
    basePackageClasses = {
        Organization.class
    }
)
@DataJpaTest(
    properties = {
        "spring.datasource.url=jdbc:tc:mysql:5.6.23:///databasename"
    }
)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class BlankJpaTest {
    @Rule
    public MySQLContainer mysql = new MySQLContainer();

    @Autowired
    private EntityManager entityManager;

    @Test
    public void test() {

    }
}

However, I get the following

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean named 'entityManagerFactory' that could not be found.
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

1 Answers1

2

Instead of @Rule, use @ClassRule and create a configuration class that would provide the DataSource.

@RunWith(SpringRunner.class)
@ContextConfiguration(
    classes = {
        BlankJpaTest.class,
        BlankJpaTest.Config.class
    }
)
@EnableJpaRepositories(
    basePackageClasses = {
        Organizations.class
    }
)
@EntityScan(
    basePackageClasses = {
        Organization.class
    }
)
@DataJpaTest(
    properties = {
        "spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
    }
)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@EnableTransactionManagement
public class BlankJpaTest {
    @ClassRule
    public static MySQLContainer mysql = new MySQLContainer();

    @Autowired
    private Organizations organizations;

    @Configuration
    static class Config {
        @Bean
        public DataSource dataSource() {

            final DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setUrl(mysql.getJdbcUrl());
            dataSource.setUsername(mysql.getUsername());
            dataSource.setPassword(mysql.getPassword());
            return dataSource;

        }
    }

    @Test
    public void test() {
        assertThat(organizations.findAll())
            .hasSize(2);

    }
}

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265