簡體   English   中英

jUnit測試中的單個Spring上下文

[英]Single Spring context in jUnit tests

我已經閱讀了很多有關此主題的建議,但似乎沒有一個起作用。 當前,為每個測試類都創建了應用程序上下文,但我希望僅創建一次並供所有測試類使用。

這是我的測試套件設置:

@RunWith(ClasspathSuite.class)
@ClassnameFilters({"org.*", ".*Test"})
public class AllTests {
}

這是我帶有上下文設置的抽象類。 所有測試類都在擴展該類。

@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
@ContextConfiguration(classes = {ServiceInitializer.Config.class})
@DirtiesContext
public abstract class ServiceInitializer extends AbstractJUnit4SpringContextTests {

@Configuration
@Import({TestConfig.class, SpringClientConfig.class})
public static class Config {
    @Bean
    public ContactsClient contactsClient(ContactsService contactsService) {
        return new ContactsClientFactory().createInstance(contactsService);         
    }
}

@Autowired
protected ContactsClient contactsService;

...

@Autowired
protected ApplicationContext appContext;


@BeforeClass
public static void setUpBeforeClass() throws Exception {
    initializeDB();
    initializeApplicationServiceProperties();
    dbInit = false;
}

protected static void initializeDB() throws Exception {
    ... database settings ...

    dropSQLTestDatabase(dbName, jdbcProperties);
    dropTestDatabase();
}

protected static void initializeApplicationServiceProperties() throws IOException {

    System.setProperty("log4j.config.file", ServiceInitializer.class.getClassLoader().getResource("log4j-test.xml").getFile());
    System.setProperty("app.config.file", ServiceInitializer.class.getClassLoader().getResource("test.properties").getFile());

    AppStartSupport.configureLogging();
    AppStartSupport.loadProperties();

}

...
}

有誰知道如何更改此設置以實現將由所有jUnit測試使用的單個上下文?

謝謝 :-)

實現此目的的一種方法是將maven surefire插件的forkCount屬性設置為1(如果您正在通過maven surfire插件運行junit測試),或者根本不在POM文件的插件聲明中將其指定為默認值。為1。這將導致應用程序上下文僅被加載一次。 在這種情況下,您需要確保在修改上下文后進行清理。

..
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.16</version>
                <dependencies>
                </dependencies>
                <configuration>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <forkCount>1</forkCount>
                </configuration>
            </plugin>
..

暫無
暫無

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

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