java – 如何在JUnit测试中初始化数据
发布时间:2020-12-15 02:24:46 所属栏目:Java 来源:网络整理
导读:我的任务是为服务层编写压力(负载)测试.主要是CRUD操作.我们使用JUnit作为测试框架,使用JUnitPerf构建负载测试,使用 Spring注入服务bean,使用hibernate访问数据库. 压力测试类似于:读取实体 – 更新实体 – 保存 – 再次读取和比较.但是为了构建测试,我需要
我的任务是为服务层编写压力(负载)测试.主要是CRUD操作.我们使用JUnit作为测试框架,使用JUnitPerf构建负载测试,使用
Spring注入服务bean,使用hibernate访问数据库.
压力测试类似于:读取实体 – 更新实体 – 保存 – 再次读取和比较.但是为了构建测试,我需要在数据库中使用一些测试数据,因此我需要在测试之前创建这些数据并在之后删除它.所需的流程:创建测试数据 – 在多个线程中运行测试 – 在所有线程完成执行后删除测试数据.有很多测试数据,所以使用一些测试转储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(); } } 我提到我需要进行负载测试以明确我不能在测试块中包含数据初始化. 我有两个问题: 解决方法
您可以使用
DBUnit为您执行数据加载.或者使用
Unitils将DBUnit与Spring和Hibernate集成在一起.
问候, (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |