How to mock JdbcTemplate.update using Jmockit?

╄→尐↘猪︶ㄣ 提交于 2019-12-24 20:43:29

问题


I'm new to Jmockit and I'm trying to mock jdbcTemplate.udpate() using the following verification,

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

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

The flushUpdate has an update query,

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

The test is to verify if update query is triggered twice.

But I'm getting the following error.

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

Does anyone has any idea ?


回答1:


Please, show your complete test code.

Either way, I think that in this case you need to do something like:

@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: is thrown when your method parameters do not match. So when you use 'any' keyword it does not look for an exact match while invoking the mocked method.

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

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



回答3:


Your job would be simpler if, rather than mocking jdbcTemplate you would encapsulate calls to jdbcTemplate in DAO classes and mock dao instead.

There is a rule do not mock API you do not own (it applies to any mocking technology) https://github.com/mockito/mockito/wiki/How-to-write-good-tests



来源:https://stackoverflow.com/questions/49736271/how-to-mock-jdbctemplate-update-using-jmockit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!