java Mockito 中的存根默认值

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

Stubbing defaults in Mockito

javamockitostubbing

提问by Alex Spurling

How can I stub a method such that when given a value I'm not expecting, it returns a default value?

我如何存根一个方法,以便在给定一个我不期望的值时,它返回一个默认值?

For example:

例如:

Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenReturn("I don't know that string");

Part 2: As above but throws an exception:

第 2 部分:同上但抛出异常:

Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenThrow(new IllegalArgumentException("I don't know that string"));

In the above examples, the last stub takes precedence so the map will always return the default.

在上面的示例中,最后一个存根优先,因此映射将始终返回默认值。

回答by Alex Spurling

The best solution I have found is to reverse the order of the stubs:

我发现的最佳解决方案是颠倒存根的顺序:

Map<String, String> map = mock(Map.class);
when(map.get(anyString())).thenReturn("I don't know that string");
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");

When the default is to throw an exception you can just use doThrow and doReturn

当默认是抛出异常时,您可以只使用 doThrow 和 doReturn

doThrow(new RuntimeException()).when(map).get(anyString());
doReturn("defg").when(map).get("abcd");
doReturn("ghij").when(map).get("defg");

https://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html#12

https://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html#12

回答by shoebox639

when(map.get(anyString())).thenAnswer(new Answer<String>() {
    public String answer(Invocation invocation) {
        String arg = (String) invocation.getArguments()[0];
        if (args.equals("abcd")
             return "defg";
        // etc.
        else
             return "default";
             // or throw new Exception()
    }
});

It's kind of a roundabout way to do this. But it should work.

这是一种迂回的方式来做到这一点。但它应该工作。

回答by Guillaume Perrot

You can use:

您可以使用:

Map<String, String> map = mock(Map.class, new Returns("I don't know that string"));
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");