【问题标题】:How to write junits for custom spring batch reader如何为自定义弹簧批处理阅读器编写junits
【发布时间】:2019-03-12 21:56:52
【问题描述】:

下面是我的自定义 Spring Batch Reader。我必须编写涵盖setPreparedStatementSetter()setRowMapper() 方法的junit。无论我尝试什么,我的单元测试都不会涵盖这些方法中的代码。有人可以指点我如何为这种匿名方法编写junit。谢谢。

PS:我知道 junit 并不是为了测试框架特定的实现方法而编写的,但我需要它来覆盖我的代码。

public class MyDataReader extends JdbcCursorItemReader<ABC> {
    public MyReader(DataSource dataSource, String beginTime, String endTime) {
      setSql(QUERY);
      setPreparedStatementSetter(new PreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            // Set parameters on the SQL query
            ps.setLong(1, Long.parseLong(beginTime.trim()));
            ps.setLong(2, Long.parseLong(endTime.trim()));
        }
      });

    setDataSource(dataSource);
    setRowMapper((ResultSet rs, int rowNum) -> {
      ABC abc = new ABC();
      abc.setDateTime(getLongOrNull("DT", rs));         
      abc.setStmt(getBooleanOrNull("SP", rs));

      return abc;
    });

   }
}

【问题讨论】:

    标签: java unit-testing junit spring-batch spring-test


    【解决方案1】:

    您可以为您的RowMapperPreparedStatementSetter 创建一个类,然后对它们进行单元测试。这是行映射器的示例:

    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.springframework.jdbc.core.RowMapper;
    
    public class ABCRowMapper implements RowMapper<ABC> {
    
        @Override
        public ABC mapRow(ResultSet rs, int rowNum) throws SQLException {
            ABC abc = new ABC();
            abc.setDateTime(rs.getLong("DT"));
            abc.setStmt(rs.getBoolean("SP"));
    
            return abc;
        }
    
    }
    

    以及相应的测试:

    import java.sql.ResultSet;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.mockito.Mockito;
    
    public class ABCRowMapperTest {
    
        @Test
        public void testABCRowMapper() throws Exception {
            // given
            ABCRowMapper rowMapper = new ABCRowMapper();
            ResultSet resultSet = Mockito.mock(ResultSet.class);
            Mockito.when(resultSet.getLong("DT")).thenReturn(1L);
            Mockito.when(resultSet.getBoolean("SP")).thenReturn(true);
    
            // when
            ABC abc = rowMapper.mapRow(resultSet, 1);
    
            // then
            Assert.assertNotNull(abc);
            Assert.assertEquals(abc.getDateTime(), 1L);
            Assert.assertTrue(abc.getStmt());
        }
    }
    

    希望这会有所帮助。

    【讨论】:

    • 谢谢,感谢您的回复!我可以尝试一下,但我不想仅仅为了代码覆盖而重构我的代码。
    • 你绝对应该!不是为了覆盖,而是为了确保您的映射逻辑按预期工作。
    • 太棒了!在这种情况下,请accept the answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多