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

时间:2018-10-28 11:53:18

标签: junit h2

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

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

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

  

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

     

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

     

将INERT插入RolleTest(created_at,bezeichnung)值(now(),“ ADMIN”)[42102-197]   java.lang.IllegalStateException:无法加载ApplicationContext

这是我的课程:

JpaConfigTest

@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

import-test.sql

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

也许有人可以告诉我我在这里想念的东西。

1 个答案:

答案 0 :(得分:0)

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

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

然后,ApplicationContext启动,在内存数据库中创建表,然后进行测试。

相关问题