首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java Futures在使用Mockito时返回null

Java Futures在使用Mockito时返回null
EN

Stack Overflow用户
提问于 2018-08-07 05:27:21
回答 5查看 4.6K关注 0票数 -1
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中应该如何模拟未来列表,这样做对吗?

EN

回答 5

Stack Overflow用户

发布于 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"))));
票数 2
EN

Stack Overflow用户

发布于 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
        // . . .
    }
票数 1
EN

Stack Overflow用户

发布于 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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51715873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档