JDBC Mocking KeyHolder

时间:2015-12-01 16:25:12

标签: java spring jdbc

尝试使用KeyHolder的Mock方法。但keyHolder为null。方法正在运行。请帮忙。需要修改测试一些如何。

@Autowired
private KeyHolderFactory factory;

@Override
public Integer createRss(String url) throws Exception {
    KeyHolder holder = factory.newKeyHolder();
    try {
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(CREATE_RSS, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, url);
                return ps;
            }
        }, holder);
    } catch (DataAccessException e) {
        throw new Exception("Rss already exist");
    }
    return holder.getKey().intValue();
}

这是我的测试体。想要模拟keyHolder,但它不起作用。

public class RSSDaoImplTest {

@InjectMocks
private RSSDaoImpl target;

@Mock
private KeyHolder keyHolder;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.mockDS = Mockito.mock(DataSource.class);
    this.mockJT = Mockito.mock(JdbcTemplate.class);

    target = new RSSDaoImpl();
    target.setJdbcTemplate(mockDS);
    target.setJdbcTemplate(mockJT);
}

@Test
public void testCreateRss() throws Exception {
    Mockito.when(mockJT.update(Mockito.any(PreparedStatementCreator.class), Mockito.any(KeyHolder.class)))
            .thenReturn(1);
    Mockito.doReturn(1).when(keyHolder).getKey().intValue();
    int actual = target.createRss("test");
    assertEquals(1, actual);
}

}

无法在stackoverflow上找到任何解决方案。提前谢谢

1 个答案:

答案 0 :(得分:2)

您可以尝试以下代码:

LSI