[英]How to run JUnit SpringJUnit4ClassRunner with Parametrized?
[英]How to run code before SpringJUnit4ClassRunner context initialization?
在我的應用程序中,我在spring應用程序啟動之前初始化屬性,如下所示
MapLookup.setMainArguments(new String[] {"logging.profile", profile}); //from args
SpringApplication.run(source, args);
(僅供參考:它用於log4j2
,必須在spring開始初始化之前設置)。
現在我想運行@IntegrationTest
,但使用相同的日志配置。 顯然我不能使用上面的代碼,因為沒有使用SpringApplication.run
執行JUnit
測試。
那么,如何在@RunWith(SpringJUnit4ClassRunner.class)
啟動之前初始化代碼呢?
注意: BeforeClass
不起作用,因為它在spring上下文啟動后執行。
您可以在靜態初始化程序中運行初始化。 靜態初始化程序將在JUnit加載測試類之后和JUnit讀取其上的任何注釋之前運行。
或者,您可以首先使用您自己的Runner初始化SpringJUnit4ClassRunner,然后運行SpringJUnit4ClassRunner
我有一個稍微不同的問題。 加載Spring上下文后,我需要在服務中部署一些東西。 解決方案使用自定義配置類進行測試,並在@PostConstruct
方法中運行部署。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class, loader = AnnotationConfigContextLoader.class)
public class JunitTest {
@Configuration
@ComponentScan(basePackages = { "de.foo })
public static class TestMConfig {
@Autowired
private DeploymentService service;
@PostConstruct
public void init() {
service.deploy(...);
}
}
@Test
public void test() {
...
}
}
也許這有幫助,有人,某個時候,某個地方;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.