亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

測試 Spring Boot 庫模塊

測試 Spring Boot 庫模塊

慕碼人8056858 2023-09-13 18:10:57
我有一個多模塊項目,其中并非每個模塊實際上都是應用程序,但其中很多都是庫。這些庫正在完成主要工作,我想在它們的實現位置測試它們。庫的當前依賴項:implementation 'org.springframework.boot:spring-boot-starter'testImplementation 'org.springframework.boot:spring-boot-starter-test'在主要源代碼中是一個帶有@Configuration單個 bean 的類:@Bean public String testString() { return "A Test String"; }我有2個測試班:@RunWith(SpringRunner.class)@SpringBootTest@ActiveProfiles({"default", "test"}) public class Test1 {      @Test    public void conextLoaded() {    }}-@RunWith(SpringRunner.class)@SpringBootTest@ActiveProfiles({"default", "test"}) public class Test2 {      @Autowired    private String testString;     @Test    public void conextLoaded() {    }}第一次測試有效。第二個沒有。該項目中沒有@SpringBootApplication任何地方,因此在與測試相同的包中我添加了測試配置:@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan("com.to.config") public class LibTestConfiguration {}但它不起作用。對于 的類也是如此@Service。它們不在上下文中。我怎樣才能讓它像一個普通的 Spring boot 應用程序一樣運行,而不需要它真正成為一個應用程序并從我需要的配置文件中加載配置和上下文?默認配置文件和測試配置文件共享它們的大部分屬性(目前),我希望它們像啟動 tomcat 一樣加載。
查看完整描述

2 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

我切換到 JUnit 5 并使它有點工作......所以如果你想測試數據庫的東西:


@DataMongoTest

@ExtendWith(SpringExtension.class)

@ActiveProfiles({"default", "test"})

class BasicMongoTest { ... }

允許您自動裝配所有存儲庫和 mongo 模板

使用 aplicaton.yml 配置進行初始化

不初始化或配置攔截器

如果您的類路徑中有一個類,則完整的應用程序上下文測試@SpringBootApplication(可以是測試上下文中的空測試 main)


@SpringBootTest

@ExtendWith(SpringExtension.class)

@ActiveProfiles({"default", "test"})

public class FullContextTest { ... }

使用所有配置和 bean 初始化完整上下文

如果沒有必要,就不應該這樣做,因為它會加載所有應用程序上下文,并且有點違背了單元測試僅激活所需內容的目的。

僅測試特定組件和配置:


@SpringBootTest(classes = {Config1.class, Component1.class})

@EnableConfigurationProperties

@ExtendWith(SpringExtension.class)

@ActiveProfiles({"default", "test"})

public class SpecificComponentsTest { ... }

僅使用 Config1 和 Component1 類初始化上下文。Component1 和 Config1 中的所有 bean 都可以自動裝配。


查看完整回答
反對 回復 2023-09-13
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

我已經解決了在根測試包路徑中添加一個SpringAppConfiguration類的問題


@SpringBootConfiguration

@ComponentScan

@EnableAutoConfiguration

public class SpringAppConfiguration {


    public static void main(String[] args) {

        SpringApplication.run(SpringAppConfiguration.class, args);

    }

}


查看完整回答
反對 回復 2023-09-13
  • 2 回答
  • 0 關注
  • 106 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號