簡體   English   中英

如何將帶有@SpringBootApplication 的 maven 模塊添加到另一個 maven 模塊作為測試 scope 的依賴項

[英]How to add a maven module with @SpringBootApplication to another maven module as a dependency in test scope

我有一個多模塊項目,其中只有根模塊具有帶有@SpringBootApplication 的 class。 其他模塊作為依賴項添加到根模塊的 POM 文件中。 為了測試其他模塊,我創建了一個帶有 @SpringBootApplication 注釋的模塊(我們稱之為測試模塊) class 和其他測試類,以在模塊測試中運行 spring 上下文。 我添加了 test-module 作為對其他模塊的依賴項,但是當我使用 maven 運行測試時,spring 上下文沒有運行。 如何正確添加?

項目結構:

---> root (this module starts spring context)
|
|--- moduleA
|
|--- moduleB

我想測試 moduleA 和 moduleB,所以我創建了一個帶有所需依賴項的測試模塊和帶有 @SpringBootApplication 注釋的 class

|--- test-module (module with @SpringBootApplication)
|
|---> moduleA (test-module as dependency in test scope)
|
|---> moduleB (test-module as dependency in test scope)

如果您的模塊沒有@SpringBootApplication,您應該在junit 測試代碼中使用@ContextConfiguration 而不是@SpringBootTest。

首先,您在 /src/test 下定義一個 class,可能稱為“TestConfig”,使用 @Configuration 和 @ComponentScan 導入要測試的 bean。

其次,您在 junit 測試的 header 中使用 @ContextConfiguration(classes = {TestConfig.class})。

以下是示例代碼:

TestConfig.java

@Configuration
@ComponentScan(basePackages = {"com.xxx"}) // base package of module or what package you want to import. you can write more ones if there are more than one package.
public class TestConfig {
}

Junit 測試

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class TestServiceA {

    @Autowired
    public ServiceA serviceA;

//...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM