簡體   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