【发布时间】:2018-04-16 05:28:27
【问题描述】:
我正在使用 Spring Boot 1.5.8.Release 并在内存数据库中使用 H2 编写测试用例。目前在每个测试用例类中,我们都有 @Before 注解,我们使用 Spring Data 类插入数据。
我想知道,我是否可以在项目中为所有测试用例定义数据。 数据库表是由 Hybernate 使用实体类创建的。唯一需要的是在每个测试用例类中从单个位置插入数据,而不是从 @Before 插入数据。
我尝试使用包含 Insert 语句的 data.sql,但使用它,Spring 不会生成模式对象(表),因此我得到 table not found 错误。我不想为 schema.sql 中的每个表指定 Create Table 语句
application-test.yml
spring:
datasource:
url: jdbc:h2:mem:test;
driverClassName: org.h2.Driver
username: sa
password:
jpa:
database: h2
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create
naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
properties:
hibernate:
show_sql: true
format_sql: false
Schema.sql
CREATE SCHEMA AB AUTHORIZATION SA;
AbcControllerTest.java
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
@SpringBootTest(classes = WebApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AbcControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private LeDataService leDataService;
@Before
public void setup() {
MyInfo myInfo = new MyInfo();
..............
..............
leDataService.save(myInfo);
}
@Test
public void getAbcTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/Abcs/1234567/12345678")
.with(SecurityMockMvcRequestPostProcessors.user("test").password("test123"))
.with(SecurityMockMvcRequestPostProcessors.csrf()))
.andExpect(status().isOk())
}
}
【问题讨论】:
-
你可以看这里:stackoverflow.com/questions/38040572/… 特别是这个答案适用于你的情况:stackoverflow.com/a/38047021/5371736
标签: spring-boot