問題描述
我正在使用 Mockito 1.9.0.我將如何驗(yàn)證一個(gè)方法是否只被調(diào)用了一次,并且傳遞給它的一個(gè)字段是否包含某個(gè)值?在我的 JUnit 測試中,我有
I'm using Mockito 1.9.0. How would i verify that a method got called exactly once, and that one of the fields passed to it contained a certain value? In my JUnit test, I have
@Before
public void setupMainProg() {
// Initialize m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc
...
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
} // setupMainProg
@Test
public void testItAll() throws GeneralSecurityException, IOException {
m_prog.work();
}
方法work"調(diào)用方法m_orderSvc"(傳遞給對象的參數(shù)之一).m_orderSvc"又包含一個(gè)成員字段m_contractsDao".我想驗(yàn)證m_contractsDao.save"是否被調(diào)用了一次,并且傳遞給它的參數(shù)是否包含某個(gè)值.
The method "work" calls a method of "m_orderSvc" (one of the arguments passed in to the object). "m_orderSvc," in turn contains a member field, "m_contractsDao". I want to verify that "m_contractsDao.save" got called exactly once and that the argument passed to it contains a certain value.
這可能有點(diǎn)令人困惑.讓我知道如何澄清我的問題,我很樂意這樣做.
This may be a little confusing. Let me know how I can clarify my question and I'm happy to do so.
推薦答案
首先你需要創(chuàng)建一個(gè)m_contractsDao并進(jìn)行設(shè)置.假設(shè)類是 ContractsDao:
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
然后將 mock 注入 m_orderSvc 并調(diào)用您的方法.
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
最后,驗(yàn)證 mock 是否被正確調(diào)用:
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
這篇關(guān)于使用 Mockito,我如何驗(yàn)證一個(gè)方法是用某個(gè)參數(shù)調(diào)用的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!