我希望有一个可以动态创建特定类的模拟对象的方法。
static Scanner mockScanner(int personsEntering, int personsLeaving) {
Scanner scanner = mock(Scanner.class);
when(scanner.readyToProcessPerson()).thenReturn(true);
when(scanner.personWantsToEnter()).thenReturn(true).thenReturn(true).thenReturn(false);
return scanner;
}Scanner中的personWantsToEnter()方法将返回true或false,这取决于一个人是想进入还是离开。我希望我的方法mockScanner()返回一个模拟对象,根据参数'personsEntering‘和'personsLeaving’来模拟进出的人。(例如:当'personsEntering‘为2,'personsLeaving’为1时,模拟对象的行为应该像上面的代码示例所示的那样。)是否有可能这样做?
发布于 2020-07-05 19:27:13
您可以在一个thenReturn()循环中动态调用for(),这取决于给定的参数personsEntering和personsLeaving。每次您必须更新从OngoingStubbing<Boolean>方法获得的when()变量。您的代码可能如下所示:
public static Foobar mockFoobar(int personsEntering, int personsLeaving) {
Foobar f = Mockito.mock(Foobar.class);
OngoingStubbing<Boolean> stub = Mockito.when(f.personWantsToEnter());
for (int i=0; i<personsEntering; i++) {
stub = stub.thenReturn(true);
}
for (int i=0; i<personsLeaving; i++) {
stub = stub.thenReturn(false);
}
return f;
}(我将Scanner替换为Foobar,以避免与java.util.Scanner__混淆)
请参阅下面的单元测试,它将根据给定的mockFoobar()调用通过
@Test
void test() throws Exception {
Foobar test = mockFoobar(4, 2);
Assertions.assertTrue(test.personWantsToEnter());
Assertions.assertTrue(test.personWantsToEnter());
Assertions.assertTrue(test.personWantsToEnter());
Assertions.assertTrue(test.personWantsToEnter());
Assertions.assertFalse(test.personWantsToEnter());
Assertions.assertFalse(test.personWantsToEnter());
}https://stackoverflow.com/questions/62744821
复制相似问题