如何使用Jmockit模拟JdbcTemplate.update



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

有人知道吗?

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

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

@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;
        }};
    }
}

mockit.internal.MissingInvocation: 缺少 1 次调用 to: 时,当您的方法参数不匹配时,将引发。因此,当您使用"any"关键字时,它在调用模拟方法时不会查找完全匹配项。

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

嘲笑 jdbcTemplate,而是将对 jdbcTemplate 的调用封装在 DAO 类中并模拟 dao,你的工作会更简单。

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

最新更新