[英]H2 database with Multiple Test Classes in SpringBoot
在我的 SpringBoot 應用程序中,我在/src/test/java
中有一個測試類。
用於測試(單元測試)。 我想使用 In memory H2 數據庫。 我有以下數據庫網址
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/schema.sql'\\;runscript from 'classpath:/data.sql'
所以當我運行測試時。 數據庫已創建並且腳本( schema.sql
和data.sql
)按預期正確運行。 它創建了一些表並將一些測試數據放在那里。
現在的問題是我添加了另一個測試類並在那里編寫了一些測試。 所以現在發生的事情是,第一個測試類成功運行,但是當第二個類加載時,它會嘗試在內存 H2 數據庫上再次運行腳本( schema.sql
和data.sql
)。 這顯然失敗了。 因為這些表已經存在於數據庫中。
誰能建議我如何實現我想要的行為。 這樣我的腳本應該只運行一次,然后所有的測試類都應該使用同一個數據庫。
我的測試類示例如下
@RunWith(SpringRunner.class)
@SpringBootTest()
public class CreateServiceTest {
@Autowired
private CreateRepo repo;
@Test
public void testCreation(){
// test code here
}
使用 spring boot,可以為每個測試唯一地定義 h2 數據庫。 只需覆蓋每個測試的數據源 URL
@SpringBootTest(屬性 = {"spring.config.name=myapp-test-h2","myapp.trx.datasource.url=jdbc:h2:mem:trxServiceStatus"})
測試可以並行運行。
參考: https ://stackoverflow.com/a/49644877
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.