我在尝试进行单元测试时遇到问题。
测试类很简单,例如:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/job-runner-context.xml})
public class AtualizarDataServiceTest {
@Autowired
DataSource testDataSource;
@Autowired
Service service;
@Before
public void setUp() throws DatabaseUnitException, SQLException{
service.setDataSource(testDataSource);
}
@Test
public final void testUpdateDate() throws SQLException {
assertTrue(verifyDate());
service.updateDate();
assertFalse(verifyDate()); //Assert brokes here
}
private boolean verifyDate(){
SimpleJdbcTemplate consultaTemplate = new SimpleJdbcTemplate(testDataSource);
int count = consultaTemplate.queryForInt("SELECT COUNT(*) FROM MY_TABLE");
return count == 0;
}
}
服务:
public class Service {
private DataSource dataSource;
public void updateDate(){
SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(getDataSource());
String query = "UPDATE MY_TABLE SET DT_UPDATE_OPERATION = ?";
jdbcTemplate.update(query, new Object[]{new java.sql.Date(Calendar.getInstance().getTime().getTime())});
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
job-runner-context.xml
重要部分:
<context:annotation-config/>
<context:component-scan base-package="my.package"/>
<bean class="my.package.Service"/>
<bean id="testDataSource" class="com.read.only.MyBasicDataSource" destroy-method="close" lazy-init="true">
<property name="jdbcReference" value="derby" />
</bean>
jdbc 连接属性:
<com:jdbcReference name="derby" type="DATABASE">
<com:credential user="" password="" />
<com:autocommit arg="false" />
<com:databaseConfig driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby:dbderby;create=true" databaseName="ANY" />
</com:jdbcReference>
起初,我认为问题与提交问题有关,但我尝试将自动提交属性的值设置为“true”并手动调用testDataSource.getConnection().commit()
,但它没有用。代码和方法运行良好,但测试没有更新 derby 数据库。在其他测试类中,数据预设dbUnit
在同一数据库中并且代码有效。这个答案在这里给出了我检查的可能问题的一般列表,我正在读取和写入相同模式中的相同表。我错过了什么吗?