Class A
{
public B makeB(int q)
{
return new B(q);
}
public boolean evaluate(int q)
{
B b = makeB(q);
boolean result = b.get();
return result;
}
}
Class B
{
int e;
public B(int w)
{
e=w;
}
public boolean get()
{
//return boolean based on object B
}
}
Class ATest
{
A a = spy(A.class);
B b1 = mock(B.class);
B b2 = mock(B.class);
doReturn(b1).when(a).makeB(5);
doReturn(b2).when(a).makeB(10);
when(b1.get()).thenReturn(true);
when(b2.get()).thenReturn(false);
a.evaluate();
}
=======================
在这里,当对象 B 包含值 5 时,我想从方法 evaluate 返回 true,如果它包含值 10,则返回 false。
B 类来自外部库。
单元测试和 mockito 的新手。
最佳答案
其他答案在技术上是正确的,但首先要理解的是:您应该努力不使用这样的模拟框架。
请记住:模拟框架的目的只是使测试成为可能/更容易。你的模拟规范应该尽可能简单。意思是:与其考虑让模拟在不同的参数上给出不同的结果 - 更好的解决方案是进行不同的测试和模拟规范,例如:
@Test
public void testFooWithA() {
when(someMock.foo(eq(whateverA)).thenReturn(bar);
...
@Test
public void testFooWithB() {
when(someMock.foo(eq(whateverB)).thenReturn(somethingElse);
...
在某些情况下,您会编写更复杂的代码来使您的模拟“更智能”。但大多数时候,当我不得不这样做时 - 我退后一步,简化我的测试设计。换句话说:当您的测试变得“太复杂”时——最常见的原因是测试中的类/方法太复杂。
关于java - 莫基托。如何基于模拟对象作为参数返回 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083732/