gpt4 book ai didi

java - 在 Spring TestContext 中使用 DbUnit 的问题

转载 作者:行者123 更新时间:2023-11-30 09:52:28 25 4
gpt4 key购买 nike


我正在尝试单独测试我的 DAO 层(基于 JPA 构建)。在单元测试中,我使用 DbUnit 填充数据库并使用 Spring Test 获取 ApplicationContext 的实例。

当我尝试使用 SpringJunit4ClassRuner 时,ApplicationContext 被注入(inject),但 DbUnit 的 getDataSet() 方法从未被调用。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...

然后我尝试删除 @RunWith 注释,这消除了 getDataSet() 方法的问题。但是现在我不再注入(inject) ApplicationContext 实例。我尝试使用 @TestExecutionListeners 注释,默认情况下它应该配置 DependencyInjectionTestExecutionListener,但 AppContext 仍然没有被注入(inject)。

@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...

有人有什么想法吗?结合这两个框架通常是个坏主意吗?


编辑:这是测试类的其余源代码:

@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {

static final String TEST_DB_PROPS_FILE = "testDb.properties";
static final String DATASET_FILE = "testDataSet.xml";
static Logger logger = Logger.getLogger( SimpleJPATest.class );
private ApplicationContext ctx;

public SimpleJPATest() throws Exception {
super();
setDBUnitSystemProperties(loadDBProperties());
}

@Test
public void testSimple() {
EntityManagerFactory emf = ctx.getBean("entityManagerFactory", EntityManagerFactory.class);
EntityManager em = emf.createEntityManager();
GenericDAO<Club> clubDAO = new JpaGenericDAO<Club>(ClubEntity.class, "ClubEntity", em);
em.getTransaction().begin();
Collection<Club> allClubs = clubDAO.findAll();
em.getTransaction().commit();
assertEquals(1, allClubs.size());
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}

private void setDBUnitSystemProperties(Properties props) {
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
props.getProperty("db.driver"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
props.getProperty("db.url"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
props.getProperty("db.username"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
props.getProperty("db.password"));

}

private Properties loadDBProperties() throws Exception {
URL propsFile = ClassLoader.getSystemResource(TEST_DB_PROPS_FILE);
assert (propsFile != null);
Properties props = new Properties();
props.load(propsFile.openStream());
return props;
}

@Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty( DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new HsqldbDataTypeFactory() );
}

@Override
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.CLEAN_INSERT;
}

@Override
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE_ALL;
}

@Override
protected IDataSet getDataSet() throws Exception {
logger.debug("in getDataSet");
URL dataSet = ClassLoader.getSystemResource(DATASET_FILE);
assert (dataSet != null);
FlatXmlDataSet result = new FlatXmlDataSetBuilder().build(dataSet);
return result;
}
}

最佳答案

我已经将这两个框架一起使用,没有任何问题。为了使其正常工作,我不得不做一些与标准略有不同的事情:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class MyDaoTest extends DBTestCase {

@Autowired
private MyDao myDao;

/**
* This is the underlying BasicDataSource used by Dao. If The Dao is using a
* support class from Spring (i.e. HibernateDaoSupport) this is the
* BasicDataSource that is used by Spring.
*/
@Autowired
private BasicDataSource dataSource;

/**
* DBUnit specific object to provide configuration to to properly state the
* underlying database
*/
private IDatabaseTester databaseTester;

/**
* Prepare the test instance by handling the Spring annotations and updating
* the database to the stale state.
*
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
databaseTester = new DataSourceDatabaseTester(dataSource);
databaseTester.setDataSet(this.getDataSet());
databaseTester.setSetUpOperation(this.getSetUpOperation());
databaseTester.onSetup();
}

/**
* Perform any required database clean up after the test runs to ensure the
* stale state has not been dirtied for the next test.
*
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
databaseTester.setTearDownOperation(this.getTearDownOperation());
databaseTester.onTearDown();
}

/**
* Retrieve the DataSet to be used from Xml file. This Xml file should be
* located on the classpath.
*/
@Override
protected IDataSet getDataSet() throws Exception {
final FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
builder.setColumnSensing(true);
return builder.build(this.getClass().getClassLoader()
.getResourceAsStream("data.xml"));
}

/**
* On setUp() refresh the database updating the data to the data in the
* stale state. Cannot currently use CLEAN_INSERT due to foreign key
* constraints.
*/
@Override
protected DatabaseOperation getSetUpOperation() {
return DatabaseOperation.CLEAN_INSERT;
}

/**
* On tearDown() truncate the table bringing it back to the state it was in
* before the tests started.
*/
@Override
protected DatabaseOperation getTearDownOperation() {
return DatabaseOperation.TRUNCATE_TABLE;
}

/**
* Overridden to disable the closing of the connection for every test.
*/
@Override
protected void closeConnection(IDatabaseConnection conn) {
// Empty body on purpose.
}
// Continue TestClass here with test methods.

我不得不做一些比我想做的更多的手动操作,但是如果您尝试将 JUnit Parameterized runner 与 Spring 结合使用(在这种情况下,您必须手动启动 TextContext),同样的情况也适用。需要注意的最重要的事情是我覆盖了 closeConnection() 方法并将其留空。这会覆盖每次测试后关闭数据源连接的默认操作,这会增加不必要的时间,因为每次测试后都必须重新打开连接。

关于java - 在 Spring TestContext 中使用 DbUnit 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4249081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com