我已经做了很多搜索,但是运气不好。
问题是我在测试类中使用MockMvcBuilders.webAppContextSetup(wac).build()
来调用实际Spring Boot应用程序的模拟版本。但是,由于我正在SB应用程序的服务后端中执行数据库事务,因此我想使用内存中的H2数据源进行测试(duh!)。
关于通过创建副本并将其放置在application.properties
文件夹中(覆盖数据源变量)来覆盖src/test/resources
文件的建议。我在测试类中结合以下代码片段来完成了后者:
@RunWith(SpringRunner.class)
@WebAppConfiguration("classpath:META-INF/web-resources")
@ContextHierarchy({ @ContextConfiguration(classes = Application.class) })
public class ApplicationSvcTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Autowired
private CrudRepo crudRepo;
static boolean initialized = false;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
if (!initialized) {
populateDB(crudRepo); // calling the backend service to save to DB
initialized = true;
}
}
我位于application.properties
文件夹中的src/test/resources
文件包含以下内容:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
spring.jackson.serialization.indent-output=true
server.port = 8080
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa
# ===============================
# = JPA / HIBERNATE
# ===============================
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
# Naming strategy
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
无论如何,测试服仍然尝试连接到application.properties
文件夹中src/main/resources
中定义的原始数据源,从而与真实数据库进行事务处理。
我该如何解决这个问题?