【问题标题】:How to mock JdbcTemplate.update using Jmockit?如何使用 Jmockit 模拟 JdbcTemplate.update?
【发布时间】:2018-09-19 01:09:50
【问题描述】:

我是 Jmockit 的新手,我正在尝试使用以下验证来模拟 jdbcTemplate.udpate()

    new Expectations() {{
        someRef.flushUpdates();
    }};

    new Verifications() {{
        String query;
        jdbcTemplate.update(query = withCapture(), withInstanceOf(Date.class));
        times = 1;
    }};

flushUpdate 有更新查询,

public void flushUpdates(){
  Date now = new Date();
  String query = "Update table_name set last_updated = ? ";
  jdbcTemplate.update(query,now);
}

测试是验证update查询是否被触发了两次。

但我收到以下错误。

mockit.internal.MissingInvocation: Missing 1 invocations to:
org.springframework.jdbc.core.JdbcTemplate#update(String, Object[])
with arguments: any String, an instance of java.util.Date
on mock instance: org.springframework.jdbc.core.JdbcTemplate@2d000e80

有人知道吗?

【问题讨论】:

  • 快速浏览Getting started页面。
  • 我在基类和测试类中使用了@Injectable JdbcTemplate jdbcTemplate; ,这导致从Expectation内部类调用时对象引用发生变化。从基类中删除引用解决了这个问题。

标签: java unit-testing jmockit jmock


【解决方案1】:

请出示您的完整测试代码。

无论哪种方式,我认为在这种情况下,您需要执行以下操作:

@RunWith(JMockit.class)
public class Test{

    @Tested
    private SomeClass someRef;

    @Injectable
    private JbdcTemplate jdbcTemplate;

    @Test
    public void test(){
        someRef.flushUpdates();

        new Verifications() {{
            String query;
            jdbcTemplate.update(query = withCapture(), withInstanceOf(Date.class));
            times = 1;
        }};
    }

}

【讨论】:

    【解决方案2】:

    mockit.internal.MissingInvocation: Missing 1 invocations to: 当你的方法参数不匹配时抛出。因此,当您使用 'any' 关键字时,它不会在调用模拟方法时寻找完全匹配。

    @Test
            public void test(){
                someRef.flushUpdates();
    
                new Verifications() {{
                    String query;
                    jdbcTemplate.update((String)any, (Date)any);
                    times = 1;
                }};
            }
    

    【讨论】:

    • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和文档链接。如果没有围绕它的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请编辑您的答案。
    • 虽然您的代码可能作为答案正确,但详细说明您的代码的作用,它可以提高您的答案的质量。查看文章:How do I write a good answer?
    • @LuFFy 编辑了我的答案。
    【解决方案3】:

    如果不是模拟 jdbcTemplate,而是将对 jdbcTemplate 的调用封装在 DAO 类中并模拟 dao,那么您的工作会更简单。

    有一条规则不要模拟你不拥有的 API(它适用于任何模拟技术) https://github.com/mockito/mockito/wiki/How-to-write-good-tests

    【讨论】:

    • 我自己不会模拟JdbcTemplate(或DAO,如果有的话),但如果你真的想模拟数据库访问,这样做并没有本质上的错误。请参阅relevant question
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多