spring@datajpatest

bxpogfeg  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(508)

这是对spring@datajpatest和junit5的扩展,主要区别在于添加了测试容器。
我试着在git回购样本中把事情保持在最低限度。
测试很直接

@DataJpaTest
@Testcontainers
@ContextConfiguration(classes = {
        DemoApplicationTests.Config.class
})
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class DemoApplicationTests {

    @Autowired
    private Artifacts artifacts;

    @Test
    void contextLoads() {
        assertThat(artifacts).isNotNull();
    }

    @Container
    private static final MySQLContainer<?> MYSQL = new MySQLContainer<>("mysql:5.7");

    @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());

            await().pollInterval(Duration.ofSeconds(2L))
                    .atMost(Duration.ofMinutes(2L))
                    .until(() -> {
                        try (final Connection c = dataSource.getConnection()) {
                            c.prepareStatement("select 1 from dual");
                            return true;
                        } catch (SQLException e) {
                            return false;
                        }
                    });

            return dataSource;

        }

    }

}

主要的应用程序我也保持在最低限度

@SpringBootApplication
@EnableTransactionManagement
@EnableJpaRepositories
@EntityScan
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

但运行测试时,我得到以下堆栈跟踪段:

Caused by: java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages
    at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:78)
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:79)
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport$AutoConfiguredAnnotationRepositoryConfigurationSource.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:138)
    at org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.lambda$getCandidates$2(RepositoryConfigurationSourceSupport.java:82)
hujrc8aj

hujrc8aj1#

我找到了两种方法让它工作。一种方法是

@ContextConfiguration(classes = {
  DemoApplication.class,
  DemoApplicationTests.Config.class
})

从中加载配置 DemoApplication . 虽然它通常比较干净,但是如果您有其他服务,比如enableredisrepositories和enablekafka,测试仍然可能失败,因为这些资源可能没有在您的脚本中配置。
或者 Config 类可以启用,因此只执行jpa测试。这是我最终选择的,因为我在从中提取样本的代码上启用了redisrepositories。

@Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories
    @EntityScan
    static class Config

相关问题