class Student{
int age;
String name;
}
class Demo{
public void getStudentList() {
Future<List<Student>> future = client.getAsyncData();
List<Student> response = futures.get(100l, TimeUnit
.MILLISECONDS);
}
}
class StudentTest{
@Test
public testData(){
List<Student> students = new ArrayList();
Client client = ClientFactory.getInstance();
Future<List<Student>> mockFuture = mock(Future.class);
when(client.getAsyncData()).thenReturn(mockFuture);
when(mockFuture.get(10l,TimeUnit.MILLISECONDS)).thenReturn(students);
Demo demo = mock(Demo.class);
demo.getStudentList();
}
**我正在获取学生列表对象为空**客户端是第三方服务,它是抽象的
//在Java中应该如何模拟未来列表,这样做对吗?
发布于 2019-01-31 02:39:31
尝试将已初始化的学生对象列表作为list返回,并将anyInt()或anyString()作为get()方法的参数传递。
请让我知道以下解决方案是否适用于您,如果不适用,请发布错误日志:
Future<List<Student>> mockFuture = Mockito.mock(Future.class);
when(client.getAsyncData()).thenReturn(mockFuture);
when(mockFuture.get(anyInt(), any())
.thenReturn(asList(new Student(21, "A"), new Student(22, "B")));
或者,您可以尝试使用CompletableFuture创建一个已经完成的Future>。
when(mockFuture.get(anyInt(), any()))
.thenReturn(CompletableFuture.completedFuture(Arrays.asList(new Student(21, "A"), new Student(22, "B"))));
发布于 2018-08-07 05:35:58
一旦模拟了Future类,您需要将其存根以返回模拟列表对象,如下所示:
Future future = Mockito.mock(Future.class);
Mockito.when(future.get()).thenReturn(new ArrayList<>());
然后,您可以验证未来的对象为:
assertTrue(future.get() instanceof List);
assertTrue(((List) future.get()).isEmpty());
在您的例子中,应该是这样的:
@Test
public void testData(){
Client client = ClientFactory.getInstance(); // make sure client is mock
// mock future and stub it
Future mockFuture = mock(Future.class);
List<Student> students = new ArrayList<>();
when(mockFuture.get()).thenReturn(students);
// mock stub the client
when(client.getAsyncData()).thenReturn(mockFuture);
// verify
// . . .
}
发布于 2018-08-07 15:01:12
如果以下解决方案对您有效,或者您需要任何进一步的帮助/澄清,请让我知道
//sugeestion: add an access modifier for the member variables
class Student{
int age;
String name;
}
class Demo{
public void getStudentList() {
Future<List<Student>> future = client.getAsyncData();
}
}
class StudentTest{
@Test
public testData(){
/*Since its a Unit test case we must mock the other Object behavior to keep things simple and focused*/
Client client = Mockito.spy(ClientFactory.getInstance());
Future<List<Student>> mockFuture = mock(Future.class);
when(client.getAsyncData()).thenReturn(mockFuture);
}
https://stackoverflow.com/questions/51715873
复制相似问题