問題描述
我正在使用 Mockito 1.9.0.我將如何驗證一個方法是否只被調用了一次,并且傳遞給它的一個字段是否包含某個值?在我的 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"調用方法m_orderSvc"(傳遞給對象的參數之一).m_orderSvc"又包含一個成員字段m_contractsDao".我想驗證m_contractsDao.save"是否被調用了一次,并且傳遞給它的參數是否包含某個值.
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.
這可能有點令人困惑.讓我知道如何澄清我的問題,我很樂意這樣做.
This may be a little confusing. Let me know how I can clarify my question and I'm happy to do so.
推薦答案
首先你需要創建一個m_contractsDao并進行設置.假設類是 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 并調用您的方法.
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();
最后,驗證 mock 是否被正確調用:
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
這篇關于使用 Mockito,我如何驗證一個方法是用某個參數調用的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!