返回测试中值的预期列表



这是一个带有测试(junit5+mockito(的虚拟代码。如何在单元测试中强制返回预期的值列表? 我尝试使用 spy((、mock((,但我没有得到预期的值,或者有时我得到空指针异常。

class A {
}
public interface B {
public List<A> f1();
}
class X {
B o1;
public X(B y) {
o1 = y;
}
protected void x() {
List<A> results = m1();
// ...
}
protected List<A> m1() {
return o1.f1();
}
}
class XTest {
@Mock
private static B b;
@BeforeAll
public static void setUp() {
b = org.mockito.Mockito.mock(B.class);
}
@Test
public void t1() {
X s = spy(new X(b));
A p = new A();
A r = new A();
List<A> c = Arrays.asList(p, r);
when(s.m1()).thenReturn(c);         // how to enforce m1() to return c ?
}
}

尝试使用doReturn,像这样:

public class XTest {
@Mock
private B b;
@Test
public void t1() {
X s = spy(new X(b));
List<A> list = Arrays.asList(new A(), new A());
doReturn(list).when(s).m1();
//
doSomething
}
}

你测试类 X,为此你模拟类 B。永远不要模拟你想要测试的类:

class XTest {
private static B b;
@BeforeAll
public static void setUp() {
b = org.mockito.Mockito.mock(B.class);
}
@Test
public void t1() {
X s = new X(b);
A p = new A();
A r = new A();
List<A> c = Arrays.asList(p, r);
when(b.f1()).thenReturn(c);         //  m1() calls f1 and returns c 
}
}

最新更新