我的任務是編寫服務層的壓力(負載)測試。大多數是CRUD操作。我們使用JUnit作爲測試框架,JUnitPerf用於構建負載測試,Spring用於注入服務bean並通過hibernate訪問數據庫。如何在JUnit測試中初始化數據
壓力測試類似於:讀取實體 - 更新實體 - 保存 - 再次讀取並比較。但爲了構建測試,我需要在數據庫中使用一些測試數據,所以我需要在測試之前創建這些數據並在之後將其刪除。所需的處理流程:創建測試數據 - 在多個線程中運行測試 - 在所有線程完成執行後丟棄測試數據。有很多測試數據,所以使用一些測試轉儲sql文件來獲取它會好得多。所以我需要的是:將數據從文件加載到數據庫中 - 執行壓力測試 - 刪除所有加載的數據。
我使用SchemaExport來加載數據。我遇到以下異常:
org.hibernate.HibernateException: No local DataSource found for configuration - 'dataSource' property must be set on LocalSessionFactoryBean
at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.configure(LocalDataSourceConnectionProvider.java:49)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
at org.hibernate.tool.hbm2ddl.ManagedProviderConnectionHelper.prepare(ManagedProviderConnectionHelper.java:27)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:180)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:133)
.................
這裏是我的SessionFactory的bean定義:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
hibernate.show.sql=${hibernate.show.sql}
</value>
</property>
<property name="annotatedClasses">
<list>
...
my classes
...
</list>
</property>
</bean>
我初始化以下列方式測試:
@BeforeClass
public static void createTestData() throws AccessDeniedException, AccountException, SQLException {
ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext("classpath:/applicationContext_test.xml");
AnnotationSessionFactoryBean sessionFactoryBean = (AnnotationSessionFactoryBean) appCtx.getBean("sessionFactory");
org.hibernate.cfg.Configuration configuration = sessionFactoryBean.getConfiguration();
SchemaExport schemaExport = new SchemaExport(configuration);
schemaExport.drop(false, true);
schemaExport.create(false, true);
if (schemaExport.getExceptions().size() > 0) {
for (Object exception : schemaExport.getExceptions()) {
if (exception instanceof Throwable) {
((Throwable) exception).printStackTrace();
}
}
throw new IllegalStateException();
}
}
我提到了我需要進行負載測試以明確我不能在測試塊中包含數據初始化。
我有兩個問題: 1)如何在加載測試之前初始化數據並刪除它之後? 2)我是否正確?或者,也許我應該換用其他技術來進行壓力測試?
我已經安裝了Unitils,但是它在每個方法調用中都執行了DataSet插入。我需要它加載一次,然後在多個線程中執行測試方法,而無需任何額外的數據加載。 – Zalivaka 2011-04-04 10:25:42