簡體   English   中英

如何使用Jmockit模擬JdbcTemplate.update?

[英]How to mock JdbcTemplate.update using Jmockit?

我是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的調用: 因此,當您使用“ any”關鍵字時,在調用模擬方法時它不會尋找完全匹配的內容。

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

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

如果將模擬Ddb的調用封裝在DAO類和模擬dao中,而不是模擬jdbcTemplate,則您的工作將更加簡單。

有一個規則,不要嘲笑您不擁有的API(適用於任何嘲笑技術) https://github.com/mockito/mockito/wiki/How-to-write-good-tests

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM