简体   繁体   English

Mockito:mocking 包含 lambda 表达式的方法调用

[英]Mockito: mocking a method call that contains a lambda expression

I'm creating a unit test for the below Java code which gets data from a database and, via a lambda, maps the data retrieved into a list:我正在为以下 Java 代码创建一个单元测试,该代码从数据库中获取数据,并通过 lambda 将检索到的数据映射到列表中:

List<Pair<String, String>> list = jdbcTemplate.query(MY_QUERY, (rs, rowNum) -> {
    String code = rs.getString(1);
    String name = rs.getString(2);
    return new Pair<String, String>(code, name);
});

It's part of a Spring framework service class;它是 Spring 框架服务 class 的一部分; the unit test is run via SpringJUnit4ClassRunner.单元测试通过 SpringJUnit4ClassRunner 运行。

I've used Mockito to mock the jdbcTemplate object (of type NamedParameterJdbcTemplate).我使用 Mockito 来模拟 jdbcTemplate object(类型为 NamedParameterJdbcTemplate)。

I'm trying to mock the result of the jdbcTemplate.我试图模拟 jdbcTemplate 的结果。 Looking at the method call, it looks like I need to mock this method in the NamedParameterJdbcTemplate class:查看方法调用,看来我需要在 NamedParameterJdbcTemplate class 中模拟此方法:

query(String sql, RowMapper<T> rowMapper)

I have tried this:我试过这个:

List<Pair<String, String>> pairList = ...;
Mockito.when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(RowMapper.class))).thenReturn(pairList);

... but when I run the unit test, the "list" variable is always null after the line of code has been passed, as if the mock hasn't been triggered to return my value. ...但是当我运行单元测试时,在代码行通过后,“列表”变量始终是 null,就好像没有触发模拟返回我的值一样。

The Mockito object is definitely being injected into the class. Mockito object 肯定被注入到 class 中。

Printing the mock's invocactions displays this:打印模拟的调用会显示:

[Mockito] Interactions of: Mock for NamedParameterJdbcTemplate, hashCode: <n>
1. namedParameterJdbcTemplate.query("query", my.package.MyClass$$Lambda$114/1274225913@3e134896);

Is there anything I'm obviously doing wrong?有什么我明显做错了吗? Thanks in advance for any assistance.提前感谢您的任何帮助。

try Mockito.any(Function.class)尝试Mockito.any(Function.class)

Mockito.when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(Function.class))).thenReturn(pairList);

I moved the mock's configuration to where it's created:我将模拟的配置移动到它的创建位置:

@Bean(name = "jdbcTemplate")
public NamedParameterJdbcTemplate jdbcTemplate() {
    NamedParameterJdbcTemplate jdbcTemplate = Mockito.mock(NamedParameterJdbcTemplate.class);

    Pair<String, String> pair = new Pair<String, String>(CODE, NAME);
    List<Pair<String, String>> pairList = new ArrayList<Pair<String, String>>();
    pairList.add(pair);

    Mockito.when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(RowMapper.class))).thenReturn(pairList);

    return jdbcTemplate;
}

It works now.现在可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM