如果我有一个称为数量的非模拟对象(具有更新函数),而另一个模拟对象称为M,我如何更新数量对象,然后在m.dosomething时返回() 叫做。我想做这样的事情。
Quantity quantity = new Quantity(1);
M m = //...another object
when(m.doSomething()).thenReturn(quantity.update(2));
,但我不能这样做,因为update()无效。有什么方法可以调用数量更新,然后返回更新的数量?
我在想这样的事情
when(m.doSomething()).thenDo(quantity.update(2)).thenReturn(quantity);
想象一下数量也是一个模拟,当我打电话给m.dosethething时,我想触发数量。update()。
我认为您想要的就是这样:
class QuantityTest{
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
private Quantity quantity;
@Mock
private M m;
Cut cut;
@Before
public void setup(){
cut = new Cut(m,quantity);
}
@Test getsQuantitiesAsDesired(){
doReturn(1,2).when(quantity).get(); //return 1 at first call, 2 at all others
InOrder inOrder = inOrder(m,quantity);
cut.doSomethingWithQuantityAndM();
inOrder.verify(quantity).get();
inOrder.verify(m).doSomething();
inOrder.verify(quantity).get();
}
}
但是,如果您坚持更改Quantity
:
class QuantityTest{
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
private M m;
private Quantity quantity = new Quantity(1);
Cut cut;
@Before
public void setup(){
cut = new Cut(m,quantity);
}
@Test getsQuantitiesAsDesired(){
doAnswer(i->quantity.update(2)).when(m).doSomething();
// ...
我没有测试它,因此您可能需要"匿名类"表单才能void答案...
以下是您要寻找的内容:
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable{
quantity.update(2);
return quantity;
}
}).when(m).doSomething();