问题描述
我有一个示例项目,其中我尝试了不同的技术.
I have a sample project in which I experiment with different technologies.
我有以下设置:
- Spring Boot 2.3.4.RELEASE
- Flyway 7.0.1
- 测试容器1.15.0-rc2
- Junit 5.7.0
如何使用testcontainer-junit5测试存储库层?
How can I test the Repository layer with testcontainer-junit5?
我现在为CompanyRepositoryTest.java
提供的代码示例:
Example of code I have now for CompanyRepositoryTest.java
:
@ExtendWith(SpringExtension.class)
@Testcontainers
public class CompanyRepositoryTest {
@Autowired
private CompanyRepository companyRepository;
@Container
public MySQLContainer mysqlContainer = new MySQLContainer()
.withDatabaseName("foo")
.withUsername("foo")
.withPassword("secret");;
@Test
public void whenFindByIdExecuted_thenNullReturned()
throws Exception {
assertEquals(companyRepository.findById(1L), Optional.ofNullable(null));
}
@Test
public void whenFindAllExecuted_thenEmptyListReturned() {
assertEquals(companyRepository.findAll(), new ArrayList<>());
}
}
添加@SpringBootTest
时,我需要设置所有上下文并遇到一些应用程序加载上下文问题吗?
When I add @SpringBootTest
, I need to set up all the context and have some Application load context issues?
问题是,任何人都可以揭开@TestContainers
注释的作用吗?在测试存储库时,最佳做法是什么或正确使用它?
The question is, can anyone demystify what @TestContainers
annotation does? What is the best practice or correct to use it while testing the Repository?
推荐答案
如果您使用的是Spring Boot,则为测试设置测试容器的最简单方法可能是在application-test.yml
中提供属性.这将使用数据源JDBC URL来启动testcontainers容器.有关更多信息,请参考Testcontainers JDBC支持.
If you are using Spring Boot, the easiest way to setup testcontainers for your tests is probably to provide properties in application-test.yml
. This will use the datasource JDBC URL to launch the testcontainers container. Refer to Testcontainers JDBC support for more information.
您还可以使用@DataJpaTest
而不是@SpringBootTest
来仅测试存储库层:
You can also test just the repository layer by using @DataJpaTest
instead of @SpringBootTest
:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("test")
class CompanyRepositoryTest { }
您的application-test.yml
文件:
spring:
datasource:
url: jdbc:tc:mysql:8.0://hostname/databasename
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
在某些情况下,您可能还想使用@TestPropertySource
注释:
In some cases you might also want to use the @TestPropertySource
annotation instead:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(
properties = {
"spring.datasource.url = jdbc:tc:mysql:8.0://hostname/test-database",
"spring.datasource.driver-class-name = org.testcontainers.jdbc.ContainerDatabaseDriver"
}
)
class CompanyRepositoryTest { }
请注意,hostname
和test-database
实际上并没有在任何地方使用.
Please note that the hostname
and test-database
are not actually used anywhere.
这篇关于如何使用junit5和testcontainer测试存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!