我想在 Spring Boot 应用程序和测试容器中测试我的数据访问层。
在 UserRepository 上运行测试时,我得到
Caused by: org.postgresql.util.PSQLException: ERROR: relation "users" does not exist
我不知道是什么原因导致的,我什至正在使用
测试代码:
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@DataJpaTest
public class UserRepositoryTest {
@Container
static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
.withDatabaseName("test")
.withUsername("sa")
.withPassword("sa");
@DynamicPropertySource
static void setProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl);
registry.add("spring.datasource.username", postgreSQLContainer::getUsername);
registry.add("spring.datasource.password", postgreSQLContainer::getPassword);
}
@Autowired
private UserReporitory userReporitory;
@Test
public void shouldFire(){
User user = new User("abcde", "mail", "username", "pwd", "CREDENTIALS", true, true, true, true, "USER,ADMIN", null);
userReporitory.save(user);
List<User> users = userReporitory.findAll();
assertThat(users).isNotNull();
}
}
我将不胜感激任何建议:)
我尝试用谷歌搜索有关测试的信息,但似乎没有人遇到这个问题。
我只需在
/resources
目录中创建一个 init.sql 即可。 application-test.yml
文件,在其中添加了 spring.sql.init.mode: always
。 @ActiveProfiles("test")
注释来使用此配置文件。
它就像一个魅力:)