如何使用BeanPropertyRowMapper模拟jdbcTemplate查询?

huangapple go评论83阅读模式
英文:

How to mock jdbctemplate query with beanpropertyrowmapper?

问题

question, how can i mock this method ?

return jdbcTemplate.query(query.toString(), new BeanPropertyRowMapper<>(TarjetaCoordenada.class), id);

@Override
public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException {
    return result(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper)));
}

This is my current code, all i need to do is find out how to mock the JDBC query method with the arguments above.

@ExtendWith(MockitoExtension.class)
class TipoEstadoRepositoryTests {

    @Mock
    private JdbcTemplate jdbcTemplate;

    @InjectMocks
    private TipoEstadoRepository repository;

    @Test
    void shouldValidateConsultar() {
        when(repository.consultar(Mockito.anyString())).thenReturn(null);
        Assertions.assertNull(repository.consultar("abc"));
    }

}
英文:

question, how can i mock this method ?

return jdbcTemplate.query(query.toString(), new BeanPropertyRowMapper&lt;&gt;(TarjetaCoordenada.class), id);

@Override
	public &lt;T&gt; List&lt;T&gt; query(String sql, RowMapper&lt;T&gt; rowMapper, @Nullable Object... args) throws DataAccessException {
		return result(query(sql, args, new RowMapperResultSetExtractor&lt;&gt;(rowMapper)));
	}

This is my current code, all i need to do is find out how to mock the JDBC query method with the arguments above.

@ExtendWith(MockitoExtension.class)
class TipoEstadoRepositoryTests {
	
	@Mock
	private JdbcTemplate jdbcTemplate;
	
	@InjectMocks
	private TipoEstadoRepository repository;
	
	@Test
	void shouldValidateConsultar() {
		when(repository.consultar(Mockito.anyString())).thenReturn(null);
		Assertions.assertNull(repository.consultar(&quot;abc&quot;));
	}

}

答案1

得分: 2

这应该可以工作:

when(jdbcTemplate.query(yourQuery, new BeanPropertyRowMapper<TarjetaCoordenada>(TarjetaCoordenada.class), yourId)).thenReturn(yourResult)

或者:

when(jdbcTemplate.query(eq(yourQuery), any(), eq(yourId))).thenReturn(yourResult)

yourQueryyourIdyourResult 替换为预期的测试值。

英文:

This should work:

when(jdbcTemplate.query(yourQuery, new BeanPropertyRowMapper&lt;&gt;(TarjetaCoordenada.class), yourId)).thenReturn(yourResult)

Or:

when(jdbcTemplate.query(eq(yourQuery), any(), eq(yourId))).thenReturn(yourResult)

Replace yourQuery, yourId and yourResult with the expected test values.

huangapple
  • 本文由 发表于 2020年9月7日 23:11:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63780238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定