java 如何在这个模拟对象中设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31426888/
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-11-02 18:35:58  来源:igfitidea点击:

How to set the value in this mock object

javamockito

提问by Prasoon Gupta

How to set the value in mock object below. I know how to get the value but how do set the value using mock?

如何在下面的模拟对象中设置值。我知道如何获取值但如何使用模拟设置值?

    public class AUTest
    {

    Set<String> permissionIds = new HashSet<String>();

    @Mock 
    UserService userservice;

    @Mock
    PermissionService permissionservice;

    Set<String> emailid = new HashSet<String>();


    @Test
    public void getSuperUserPermissions()
    {
        List<Permissions> allPermissions = permissionservice.getAllPermissions();
        PermissionService permission = Mockito.mock(PermissionService.class);
        Mockito.when(permission.getPermissionById(5L)).thenReturn(pemission);
        Assert.assertNotNull(allPermissions);
    }

}

回答by lopisan

Mock objects are used just to get values. You can setup what values are returned, just like jou did using:

模拟对象仅用于获取值。您可以设置返回的值,就像 jou 使用的一样:

Mockito.when(permission.getPermissionById(5L)).thenReturn(pemission);

Now when you call permission.getPermissionById(5L)you'll get permission.

现在,当你打电话时,permission.getPermissionById(5L)你会得到permission

Maybe you are talking about capturing parameters passed to the method. You can do it using ArgumentCaptor.

也许您正在谈论捕获传递给方法的参数。您可以使用ArgumentCaptor 来完成

Sample code:

示例代码:

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());