简体   繁体   中英

How to mock JdbcTemplate.update using Jmockit?

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 ?

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

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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