简体   繁体   English

在Mockito中存根默认值

[英]Stubbing defaults in Mockito

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. 在上面的示例中,最后一个存根优先,因此映射将始终返回默认值。

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

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");
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. 但它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM