在测试中避免使用 @SpringBootTest 连接数据库的仓库,可以使用以下解决方法:
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
@DataJpaTest
public class UserRepositoryTest {
// 测试代码
}
import org.springframework.boot.test.mock.mockito.MockBean;
@SpringBootTest
public class UserRepositoryTest {
@MockBean
private UserRepository userRepository;
// 测试代码
}
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
public class UserRepositoryTest {
// 测试代码
}
在 test.properties 文件中,配置 H2 数据库的连接信息:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
以上是三种常用的解决方法,可以根据具体的需求选择合适的方式来避免在测试中使用 @SpringBootTest 连接实际的数据库。