繁体   English   中英

使用 H2 数据库进行单元测试

[英]Do a Unit test with an H2 database

我开始用 H2 数据库编写一些单元测试。

因此,我想从我的@Entity 创建一个表。

但是,我总是收到以下错误消息:

12:40:13.635 [main] WARN org.springframework.context.support.GenericApplicationContext - 上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.BeanCreationException:创建名为“dataSource”的 bean 时出错.wrk.fmd.config.JpaConfigTest:通过工厂方法实例化Bean失败;

未找到表“ROLLETEST”; SQL语句:

INSERT INTO RolleTest(created_at, bezeichnung) VALUES (now(), 'ADMIN') [42102-197] java.lang.IllegalStateException: 无法加载 ApplicationContext

这是我的课程:

配置测试

@Configuration
@EnableJpaRepositories
@PropertySource("application.propertiesTest")
@EnableTransactionManagement
public class JpaConfigTest {


@Autowired
private Environment env;
 
@Bean
public DataSource dataSource() {
    DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1", "sa", null);
    new ResourceDatabasePopulator(new ClassPathResource("/import-test.sql")).execute(dataSource);

    return dataSource;
}
}

InMemoryDbTest:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
  classes = { JpaConfigTest.class }, 
  loader = AnnotationConfigContextLoader.class)
@Transactional
@WebMvcTest
public class InMemoryDbTest {
 
@Resource
private StudentRepository studentRepository;
 
@Test
public void givenStudent_whenSave_thenGetOk() {
    Student student = new Student(1, "john");
    studentRepository.save(student);
     
    List<Student> student2 = studentRepository.findAll();
}
}

application.propertiesTest

server.port=8080
server.error.whitelabel.enabled=false

# H2
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

导入-test.sql

INSERT INTO RolleTest(created_at, bezeichnung) VALUES (now(), 'ADMIN');

也许有人可以告诉我我在这里缺少什么。

抱歉,这么晚才回复,但最近几天我生病了。 我做错的是我不知道在这里进行集成测试。 因此,在进行测试之前必须完成一些步骤。 我将 application-test.properties 复制到我的 application.properties 文件之外。 然后我将我的主要测试类注释如下:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")

然后 ApplicationContext 启动,在我的内存数据库中创建我的表,我可以做我的测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM