簡體   English   中英

具有自定義應用程序上下文的 Spring 集成測試

[英]Spring integration test with custom application context

對於我的應用程序,我創建了我自己的ApplicationContext類型,它允許我以可能應用程序所需的特定方式進行交互。 由於該應用程序是桌面應用程序,因此我創建了這樣的上下文:

@SpringBootApplication
@Import(StandaloneConfiguration.class)
@PropertySource(value = {"application.properties", "server.properties"})
public class OpenPatricianApplication extends Application {
    private ApplicationContext context;
    @Override
    public void init() {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(OpenPatricianApplication.class);
        context = builder.contextClass(DependentAnnotationConfigApplicationContext.class).run(getParameters().getRaw().toArray(new String[0]));
        // more initialisation

        }
    }
}

現在我想創建一個 Spring Boot 集成測試,它實際上依賴於我自己的ApplicationConext實現的功能。

@SpringBootTest(classes = {ServerTestConfiguration.class})
public class ServerIntegrationTest {
    private DependentAnnotationConfigApplicationContext context;
}

如何在測試中初始化我的context 必須創建context才能啟動 spring 應用程序,但是當輸入構造函數時,使用SpringBootTest注釋這已經發生了。 是否有任何可以應用的現有注釋或參數? 這些性質的測試是否應該完全不使用SpringBootTest注釋並手動創建應用程序?

我發現解決此問題的方法是完全放棄SpringBootTest注釋,並將上下文構造為構造函數的一部分。 或者,您也可以在BeforeAllBeforeEach方法中執行此操作,但由於我的測試類擴展了一個需要注入一些 bean 的基類,因此構造函數似乎是正確的選擇。

然而,通過構造函數注入的方式在超類中注入 bean 是行不通的,因為對超級構造函數的調用必須是構造函數中的第一個調用,這將需要為上下文提供一個靜態初始化塊,我想要盡可能避免靜態的東西,特別是如果在測試結束時沒有正確清理上下文,它將作為內存中加載類的一部分存在並可能消耗大量內存。

所以這是代碼:

public class ServerIntegrationTest extends SaveLoadBase<CityWall> {

    public CityWallSerializationTest() {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(ServerTestConfiguration.class);
        DependentAnnotationConfigApplicationContext context = (DependentAnnotationConfigApplicationContext) builder.contextClass(DependentAnnotationConfigApplicationContext.class).run();
        setContext(context);
        setClientServerEventBus((AsyncEventBus) context.getBean("clientServerEventBus"));
        setLoadAndSaveService(context.getBean(TestableLoadAndSaveService.class));
    }
}

暫無
暫無

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

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