使用 any() 或 anyList() 时,使用 ArrayList/List 参数清除方法失败

我有一个java类。


class Blah{

        public Blah(){


        }

        public String testMe(List<String> s){

            return new String("hello "+s.get(0));

        }



        public String testMeString(String s){

            return new String("hello "+s);

        }



    }

我无法尝试成功地存根和测试 testMe 方法。请注意,我只是想了解 java 中的模拟。例如我试过:


    @Test

    public void testTestMe(){

        Blah blah = spy(new Blah());

        ArrayList<String> l = new ArrayList<String>();

        l.add("oopsie");

        when(blah.testMe(Matchers.any())).thenReturn("intercepted");

        assertEquals("intercepted",blah.testMe(l));

这将返回 NullPointerException。我也尝试过任何(List.class),任何(ArrayList.class)。我也尝试过使用anyList(),但这给了我一个 IndexOutOfBounds 错误。我究竟做错了什么?有趣的是,我的testMeString作品很好。如果我做


@Test

    public void testTestMeString(){

        Blah blah = spy(new Blah());

        when(blah.testMeString(any())).thenReturn("intercepted");

        assertEquals("intercepted",blah.testMeString("lala"));

}

测试通过 any() 和 any(String.class)。


慕桂英546537
浏览 169回答 3
3回答

人到中年有点甜

通过将此语句blah.testMe()包含在 中when(),它会调用真正的方法:when(blah.testMe(Matchers.any())).thenReturn("intercepted");为避免这种情况,您应该使用doReturn(...).when(...).methodToInvoke()模式。doReturn("intercepted").when(blah).testMe(Matchers.any()));您注意到使用此语法:blah.testMe()语句未在任何地方指定。所以那不叫。除了这个问题,我认为你不需要任何间谍来测试这个方法。间谍是一种非常特殊的模拟工具,仅当您别无选择时才使用它:您需要模拟被测对象,这是一种不好的做法,并且您无法重构实际代码。但在这里你可以这样做:@Testpublic void testTestMe(){&nbsp; &nbsp; Blah blah = new Blah();&nbsp; &nbsp; ArrayList<String> l = new ArrayList<String>();&nbsp; &nbsp; l.add("oopsie");&nbsp; &nbsp; assertEquals("hello oopsie",blah.testMe(l));&nbsp;}

皈依舞

您应该重新考虑 usingspy等mock。当您有外部系统、休息 web 服务、您不想在单元测试期间调用的数据库时,应该使用这些设施。在像这样的简单场景中,只需创建一些测试输入并检查输出。@Test public void testTestMeString(){&nbsp;//given&nbsp; List<String> list = Arrays.asList("aaa");&nbsp;//when&nbsp;String result = blah.testMe(list);&nbsp;//then&nbsp;assertEquals(result, "hello aaa");&nbsp;}当您有兴趣时,given, when, then请检查 BDD。

喵喔喔

您的 NullPointerException 在存根期间被抛出,而不是在测试期间。这是因为Matchers.any()实际上返回null,所以如果您在调用真正的方法时使用它,您将null作为参数传递。testMeString恰好有效,因为null + s不会导致 NullPointerException("null"改为使用字符串)。代替:when(blah.testMe(any())).thenReturn("intercepted");你需要使用doReturn("intercepted").when(blah).testMe(any());这被记录为(虽然承认不是非常清楚)作为间谍真实物体的重要陷阱!在 Mockito 文档中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java