2014-01-20 32 views
0

我已閱讀了很多關於此主題的建議,但似乎沒有一個可行。 當前應用程序上下文是爲每個測試類創建的,但是我希望它只創建一次並被所有測試類使用。jUnit測試中的單個Spring上下文

這是我的測試套件設置:

@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測試將使用的單個上下文?

感謝:-)

回答

0

一種方式實現這一目標是萬無一失的Maven插件的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> 
.. 
相關問題