【问题标题】:Stubbing defaults in MockitoMockito 中的存根默认值
【发布时间】:2011-05-12 02:37:54
【问题描述】:

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

例如:

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");

第 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"));

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

【问题讨论】:

    标签: java mockito stubbing


    【解决方案1】:
    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()
        }
    });
    

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

    【讨论】:

      【解决方案2】:

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

      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");
      

      当默认是抛出异常时,你可以使用 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

      【讨论】:

      • 感谢您的全面回答,包括doReturn()。 (doThrow() 在这种情况下是不必要的,除非保持一致性。)
      【解决方案3】:

      你可以使用:

      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");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多