2016-12-06 284 views
1

目前我使用@BootstrapWith註釋與自定義類一起使用,它只是簡單地設置了一些在測試中使用的系統屬性。但是(據我所知)這些屬性被每個實例TestContextManager來測試和TestContext都會用它時設置:Spring:@BootstrapWith用於ApplicationContext

@BootstrapWith是用於配置 了Spring TestContext框架是怎樣的一類級別註解自舉

spring.io

有沒有什麼辦法的ApplicationContext開始前一次設置屬性?

編輯:

我不能用@RunWith(SpringJUnit4ClassRunner.class)由於參數的測試,這需要@RunWith(Parameterized.class)。我使用SpringClassRuleSpringMethodRule而不是

此外,我運行不僅參數化測試,但也運行普通測試。因此,我不能簡單地延長Parameterized亞軍

+0

你的意思' System.getProperties()'? –

+0

@MaciejDobrowolski啓動ApplicationContext之前的System.setProperty() – Anton

+0

您是否必須全局設置屬性,還是每個測試套件的屬性都不相同? –

回答

1

我認爲之前ApplicationContext設置設置一些性能的最基本的方法是編寫定製的運行,這樣的:

public class MyRunner extends SpringJUnit4ClassRunner { 

    public MyRunner(Class<?> clazz) throws InitializationError { 
     super(clazz); 
     System.setProperty("sample.property", "hello world!"); 
    } 

} 

然後你可以用它代替你目前的亞軍。

@RunWith(MyRunner.class) 
@SpringBootTest 
//.... 

如果你的當前跑步者似乎被宣佈是最終的,你可以使用聚合(但我沒有測試過)而不是繼承。

Here你可以找到一個示例Gist,其中使用該跑步者並且財產得到成功解決。

更新

如果你不希望使用自定義的Runner(儘管你可以有幾個選手的每一種情況下設置屬性 - 使用參數,無參數,等等)。您可以使用@ClassRule其靜態字段/方法的工作原理 - 看看下面的例子:

@ClassRule 
public static ExternalResource setProperties() { 
    return new ExternalResource() { 
     @Override 
     public Statement apply(Statement base, Description description) { 
      System.setProperty("sample.property", "hello world!"); 
      return super.apply(base, description); 
     } 
    }; 
} 

靜態方法是放置在您的測試類。

+0

可能我應該提到它:我不能使用@RunWith(SpringJUnit4ClassRunner.class),因爲參數化測試需要@RunWIth(Parameterized.class)。我使用SpringClassRule和SpringMethodRule代替 – Anton

+0

@Anton爲什麼不擴展'Parameterized' runner? –

+0

在這種情況下,我將無法爲普通而非參數化測試設置屬性 – Anton

0

我發現,這是可能的延長AnnotationConfigContextLoader(或任何其他ContextLoader)和壓倒一切的prepareContext()方法:

@Override 
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { 
    // set properties here 
    super.prepareContext(context, mergedConfig); 
} 

不是自定義代碼,就在@ContextConfiguration註釋上測試實例指定

相關問題