java - 在测试中使用 Spring JpaRepository

标签 java spring junit spring-boot spring-data-jpa

我有带有配置的 Spring Boot 应用程序:

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
@EnableJpaRepositories(basePackages = "com.site.data.repository")
@EntityScan(basePackages = "com.site.data.entity")
@ComponentScan(basePackages = "com.*")
@SpringBootApplication
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

resources文件夹中有application.properties文件:

spring.datasource.url=...
spring.datasource.username=...
spring.datasource.password=...
spring.datasource.driverClassName=...
#...

问题:

我尝试创建一个新类,它将向数据库添加一些条目。我认为最好的解决方案是制作一个 JUnit 测试类。因此,如果有人想向我的数据库提供数据,他可以简单地运行这个特定的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebSecurityConfig.class)
public class DataFeeder {
    @Autowired
    MyRepository myRepository;

    @Test
    public void feedDB() {
        MyEntity entity = new MyEntity();
        myRepository.saveAndFlush(entity);
    }
}

但是这个配置不起作用。当然,所有存储库在项目中都运行良好。但在运行测试期间,我收到所有表都不存在的消息。例如,对于 SOME_TABLE:

Table "SOME_TABLE" not found; SQL statement:

我看到了很多关于如何测试 JpaRepository 的教程,但我不想 make test,它添加一些项目并在测试结束后删除它。我只是想在数据库中保存一些数据(但在@Test函数中)

我的配置有什么问题吗?

最佳答案

使用@SpringApplicationConfiguration而不是@ContextConfiguration。 这是 Spring-boot 应用程序测试所必需的。

关于java - 在测试中使用 Spring JpaRepository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32221457/

相关文章:

Spring boot - 将参数从拦截器传递给 Controller ​​中的方法

java - 未捕获的异常处理程序 - UiAutomator

Netbeans 中的 Java 文件

java - 如何用java提取字符串中的特定字母

java - SpringMVC 应用程序的 Swagger API 数组为空

spring - 是否可以在 Spring、Eclipselink 和 Tomcat 环境中使用@Transational?

java - 如何模拟 ResponseEntity

android - 在项目 'testDebug' 中找不到名称为 ':module' 的任务

java - scala:FOO 不能转换为 FOO

java - 如何使用 Spring Cloud Contracts 将 Stub 中的 NULL 值设置为 clientValue