第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何啟動內(nèi)存數(shù)據(jù)庫來測試 JPA 實體?

如何啟動內(nèi)存數(shù)據(jù)庫來測試 JPA 實體?

紅顏莎娜 2023-09-06 15:52:07
因為我沒有大量 JPA 經(jīng)驗,所以我想編寫一個自動化測試來確保我的 JPA 實體正在檢索我希望它們檢索的記錄。我的計劃是為我的測試啟動一個內(nèi)存中的 H2 DB,并對其執(zhí)行一些簡單的 CRUD 操作,確保數(shù)據(jù)按我的預(yù)期返回。我不知道如何讓 Spring Boot 創(chuàng)建內(nèi)存數(shù)據(jù)庫。這是我到目前為止所擁有的,但不起作用。這是創(chuàng)建我的 JPA 存儲庫的配置。這是正確的應(yīng)用程序代碼,目前正在與我實際的 Oracle DB 一起使用。@Configuration@EnableJpaRepositories("com.name.project.webservice.dao")@EntityScan("com.name.project.webservice.types")public class JpaRepositoriesConfig {    // Intentionally empty.}我將此配置導(dǎo)入到我的測試中。@RunWith(SpringRunner.class)@SpringBootTest(classes = {JpaRepositoriesConfig.class})public class JpaEntityTest {    @Test    public void test(){}}然后,我編寫一個特定于測試的屬性文件 ,src/test/resources/application.properties用測試的 H2 配置替換應(yīng)用程序的 Oracle 配置。spring.datasource.driver-class-name=org.h2.Driverspring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1最后,我將 H2 jar 添加到我的 pom.xml 中。這個 jar 的存在以及我的測試中的注釋應(yīng)該指示 Spring Boot 根據(jù)我的屬性文件啟動 H2 數(shù)據(jù)庫。<dependency>    <groupId>com.h2database</groupId>    <artifactId>h2</artifactId>    <scope>test</scope></dependency>這個錯誤讓我很驚訝。我認(rèn)為Spring Boot應(yīng)該自動給我一個entityManagerFactory;我的應(yīng)用程序從不實例化一個entityManagerFactory bean,它工作得很好。因此,如果您不介意告訴我,我是否至少走在正確配置的正確軌道上?我錯過了哪一步導(dǎo)致了這個錯誤?我需要手動聲明entityManagerFactory嗎?感謝您的幫助。編輯:這是我的應(yīng)用程序?qū)傩晕募南嚓P(guān)部分,而不是上面記錄的測試屬性文件。spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriverspring.datasource.url= <<database-url>>spring.datasource.tomcat.max-active=5spring.datasource.tomcat.initial-size=1spring.datasource.tomcat.max-wait=20000 spring.datasource.tomcat.max-idle=1
查看完整描述

2 回答

?
蝴蝶刀刀

TA貢獻(xiàn)1801條經(jīng)驗 獲得超8個贊

我能夠通過在我的測試類上使用以下注釋將內(nèi)存數(shù)據(jù)庫添加到 Spring 上下文:


@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = { JpaRepositoriesConfig.class })

@DataJpaTest

當(dāng)然,包括在我的 pom 中必要的依賴項:


<dependency>

    <groupId>com.h2database</groupId>

    <artifactId>h2</artifactId>

    <scope>test</scope>

</dependency>

如果我正在做的事情違反了任何最佳實踐,請告訴我。


查看完整回答
反對 回復(fù) 2023-09-06
?
森欄

TA貢獻(xiàn)1810條經(jīng)驗 獲得超5個贊

我確實看到您正在維護(hù)單獨的屬性文件以進(jìn)行測試,這意味著您正在使用測試屬性創(chuàng)建數(shù)據(jù)源和實體管理器并加載 spring boot 原始應(yīng)用程序上下文。所以你不需要任何額外的測試配置


@RunWith(SpringRunner.class)

@SpringBootTest

public class JpaEntityTest {


     @Test

     public void test(){}

}

您還可以使用配置文件來執(zhí)行此操作,命名application.properties并application-test.properties使用@Profile和@ActiveProfile


@RunWith(SpringRunner.class)

@SpringBootTest

@ActiveProfile("test")

@Profile("test")

public class JpaEntityTest {


     @Test

     public void test(){}

}


查看完整回答
反對 回復(fù) 2023-09-06
  • 2 回答
  • 0 關(guān)注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號