gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:53:13 27 4
gpt4 key购买 nike

我开始用 H2 数据库编写一些单元测试。
因此,我想从我的@Entity 创建一个表。
但是,我总是收到以下错误消息:

12:40:13.635 [main] WARN org.springframework.context.support.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in at.wrk.fmd.config.JpaConfigTest: Bean instantiation via factory method failed;

Table "ROLLETEST" not found; SQL statement:

INSERT INTO RolleTest(created_at, bezeichnung) VALUES (now(), 'ADMIN') [42102-197]java.lang.IllegalStateException: Failed to load ApplicationContext


这是我的类(class):
配置测试
@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.properties 文件之外,我还复制了 application-test.properties 。
然后我将我的主要测试类注释如下:

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

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

关于junit - 使用 H2 数据库进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031214/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com