Java 如何在 Mockito 中创建自定义数据类型列表的模拟?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24258076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:09:35  来源:igfitidea点击:

How to create a mock of list of a custom data type in Mockito?

javaunit-testingmockito

提问by Sourabh

I have a class User with the following definition :

我有一个 User 类,其定义如下:

class User {

  Integer id;
  String name;
  String addr;

  //getters and setters

}

Now while testing a function, I am required to return a list of mocked Users for a stub, something like:

现在,在测试一个函数时,我需要返回一个存根的模拟用户列表,例如:

Mockito.when(userService.getListOfUsers()).thenReturn(mockList);

Now this mockList could be created as the following :

现在这个 mockList 可以创建如下:

List mockList = Mockito.mock(ArrayList.class);

But this mockList could be a list of anything. I won't be able to ensure its type. Is there a way to create list of :

但是这个 mockList 可以是任何东西的列表。我将无法确定它的类型。有没有办法创建以下列表:

List<User> mockListForUser = Mockito.mock(?);

采纳答案by Duncan Jones

You probably want to populate a normal list with your mocked objects. E.g.

您可能想用模拟对象填充普通列表。例如

List<User> mockList = new ArrayList<>();

User mockUser1 = Mockito.mock(User.class);
// ...    

mockList.add(mockUser1);
// etc.

Note that by default, Mockito returns an empty collection for any mocked methods that returns a collection. So if you just want to return an empty list, Mockito will already do that for you.

请注意,默认情况下,Mockito 为任何返回集合的模拟方法返回一个空集合。所以如果你只想返回一个空列表,Mockito 已经为你做了。

回答by Jean Logeart

Use the @Mockannotation in your test since Mockito can use type reflection:

@Mock在测试中使用注释,因为 Mockito 可以使用类型反射:

@Mock
private ArrayList<User> mockArrayList;