如何使用Jmockit模拟JdbcTemplate.update?

时间:2018-04-09 15:12:43

标签: java unit-testing jmockit jmock

我是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

有没有人有任何想法?

3 个答案:

答案 0 :(得分: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;
        }};
    }

}

答案 1 :(得分:1)

mockit.internal.MissingInvocation:当您的方法参数不匹配时,将引发缺少对1的调用:因此,当您使用“ any”关键字时,在调用模拟方法时它不会寻找完全匹配的内容。

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

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

答案 2 :(得分:-1)

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

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