1

我在尝试进行单元测试时遇到问题。

测试类很简单,例如:

@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在同一数据库中并且代码有效。这个答案在这里给出了我检查的可能问题的一般列表,我正在读取和写入相同模式中的相同表。我错过了什么吗?

4

2 回答 2

1

作为我发布的问题的答案,我验证了自动提交,如果我正在写入正确的数据库,但没有检查明显的:你不能更新没有寄存器的表!查询UPDATE MY_TABLE SET DT_UPDATE_OPERATION = ?应用于空表,计数查询将始终返回 0。我刚刚配置测试以使 DbUnit 将状态从 xml 文件导入数据库。抱歉,添麻烦了。

于 2015-11-24T17:31:26.250 回答
1

尝试设置<com:autocommit arg="true" />

于 2015-11-24T15:06:51.380 回答