我正在尝试使用TestingContainers。我能够让它运行,但我的测试总是为空。我尽量避免嘲笑,而是有真实的数据。
库
@Sql("classpath:data.sql")
class OrderDataRepositoryTest extends AbstractTestConfiguration {
//@Mock
@MockBean
//@Autowired
private OrderDataRepository orderRepository;
private AutoCloseable closeable;
@BeforeEach
public void init() {
closeable = MockitoAnnotations.openMocks(this);
}
@AfterEach
void closeService() throws Exception {
closeable.close();
}
@Test
void getAllUsersTest() {
List<Order> orders = orderRepository.findAll();
orders.toString();
}
}
设置@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
public abstract class AbstractTestConfiguration {
@Container
private MySQLContainer database = new MySQLContainer("mysql:8.0");
@Test
public void test() {
assertTrue(database.isRunning());
}
}
主要
@SpringBootTest
@Sql("classpath:init.sql")
@TestPropertySource("classpath:application-test.yml")
class TentingContainerApplicationTests {
}
application.properties
spring:
application:
datasource:
url: jdbc:mysql:8.0:///test?TC_INITSCRIPT=file:src/main/resources/init.sql
driver-class-name: com.mysql.jdbc.Driver
注释掉的
//@Mock
@MockBean
//@Autowired
是我尝试过的。mock当然可以,但是我想要@services和@repository类的真实数据。
建议吗?
如果您想单独测试与数据库相关的代码(我假设您正在使用Spring Data JPA),那么@DataJpaTest
非常适合。
该注释将为您创建一个切片的Spring上下文,其中仅包含与持久性相关的bean,如:DataSource
,EntityManager
,YourRepository
。这还不包括你的服务类、@Component
类或@RestController
类。
默认情况下,该注释尝试将嵌入式内存数据库配置为DataSource
。我们可以覆盖这个(你已经用你的一些代码示例做过了)行为来使用Testcontainers:
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class OrderDataRepositoryTest {
@Container
static MySQLContainer database = new MySQLContainer("mysql:8.0");
@DynamicPropertySource
static void setDatasourceProperties(DynamicPropertyRegistry propertyRegistry) {
propertyRegistry.add("spring.datasource.url", database::getJdbcUrl);
propertyRegistry.add("spring.datasource.password", database::getPassword);
propertyRegistry.add("spring.datasource.username", database::getUsername);
}
@Autowired
private OrderDataRepository orderRepository;
@Test
void shouldReturnOrders() {
}
}
如果您想编写另一个包含所有bean并启动嵌入式servlet容器的测试,请查看编写集成测试的@SpringBootTest。
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Testcontainers
class MyIntegrationTest {
@Container
static MySQLContainer database = new MySQLContainer("mysql:8.0");
@DynamicPropertySource
static void setDatasourceProperties(DynamicPropertyRegistry propertyRegistry) {
propertyRegistry.add("spring.datasource.url", database::getJdbcUrl);
propertyRegistry.add("spring.datasource.password", database::getPassword);
propertyRegistry.add("spring.datasource.username", database::getUsername);
}
@Autowired
private ServiceA serviceA;
@Autowired
private OrderDataRepository orderDataRepository;
}
在为测试和Mockito使用Spring TestContext时,请确保理解@Mock和@MockBean之间的区别。