問題描述
我有一個(gè)方法調(diào)用,我想用 mockito 模擬.首先,我創(chuàng)建并注入了一個(gè)對(duì)象實(shí)例,將在該實(shí)例上調(diào)用該方法.我的目標(biāo)是驗(yàn)證方法調(diào)用中的對(duì)象之一.
I have a method call which I want to mock with mockito. To start with I have created and injected an instance of an object on which the method will be called. My aim is to verify one of the object in method call.
mockito 是否允許您在調(diào)用 mock 方法時(shí)斷言或驗(yàn)證對(duì)象及其屬性?
Is there a way that mockito allows you to assert or verify the object and it's attributes when the mock method is called?
例子
Mockito.verify(mockedObject)
.someMethodOnMockedObject(
Mockito.<SomeObjectAsArgument>anyObject())
我不想做 anyObject()
我想檢查參數(shù)對(duì)象是否包含一些特定字段
Instead of doing anyObject()
i want to check that argument object contains some particular fields
Mockito.verify(mockedObject)
.someMethodOnMockedObject(
Mockito.<SomeObjectAsArgument>**compareWithThisObject()**)
推薦答案
添加到 Mockito 的新功能使這變得更加容易,
New feature added to Mockito makes this even easier,
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
查看 Mockito 文檔
Take a look at Mockito documentation
如果有多個(gè)參數(shù),并且只需要捕獲單個(gè)參數(shù),請(qǐng)使用其他 ArgumentMatchers 包裝其余參數(shù):
In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:
verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
assertEquals("John", argument.getValue().getName());
這篇關(guān)于使用 mockito 驗(yàn)證對(duì)象屬性值的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!