我有一个用于JUnit测试的简单类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/mysql-datasource-context.xml"})
public class EmployeeDAOTest {
@Autowired
EmployeeDao employeeDao;
@Test
public void findAllTest() {
assertTrue(employeeDao.findByName("noname").size() == 0);
}
}
mysql-datasource-context.xml的内容如下所示:
<context:component-scan base-package="my.packages.*"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/project"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="my.packages.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
现在,该测试对于我的mysql数据库运行没有问题。
关键是我也有一个postgres数据库,并且我需要为mysql和postgres数据库运行所有测试。
我想到的唯一解决方案是使用完全相同的测试再创建一个测试类,但将其注释为
@ContextConfiguration(locations = {"classpath:/postgres -datasource-context.xml"})
并为其创建另一个数据源上下文文件。不幸的是,这种方式似乎不是一个好的解决方案。
有没有更好的方法来解决我的问题?
最佳答案
我认为最简单的解决方案是将测试类作为基础:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/mysql-datasource-context.xml"})
public class EmployeeDAOTest {
@Autowired
EmployeeDao employeeDao;
@Test
public void findAllTest() {
assertTrue(employeeDao.findByName("noname").size() == 0);
}
}
然后使用自己的配置为postgres创建一个空子类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/postgres-datasource-context.xml"}, inheritLocations=false)
public class EmployeeDAOTestPostgres extends EmployeeDAOTest {
}
正如其他建议一样,您可以更改Spring配置文件以仅包含一个。例如,您可以将数据源放在单独的上下文中并导入它或使用配置文件(有关示例,请参见here)