为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英546537 2022-12-28 10:18:25
我有一个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)。
查看完整描述

3 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

通过将此语句blah.testMe()包含在 中when(),它会调用真正的方法:


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

为避免这种情况,您应该使用doReturn(...).when(...).methodToInvoke()模式。


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

您注意到使用此语法:blah.testMe()语句未在任何地方指定。所以那不叫。


除了这个问题,我认为你不需要任何间谍来测试这个方法。

间谍是一种非常特殊的模拟工具,仅当您别无选择时才使用它:您需要模拟被测对象,这是一种不好的做法,并且您无法重构实际代码。


但在这里你可以这样做:


@Test

public void testTestMe(){

    Blah blah = new Blah();

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

    l.add("oopsie");

    assertEquals("hello oopsie",blah.testMe(l));

 }


查看完整回答
反对 回复 2022-12-28
?
皈依舞

TA贡献1851条经验 获得超3个赞

您应该重新考虑 usingspy等mock。当您有外部系统、休息 web 服务、您不想在单元测试期间调用的数据库时,应该使用这些设施。在像这样的简单场景中,只需创建一些测试输入并检查输出。


@Test public void testTestMeString(){

 //given

  List<String> list = Arrays.asList("aaa");

 //when

 String result = blah.testMe(list);

 //then

 assertEquals(result, "hello aaa");

 }

当您有兴趣时,given, when, then请检查 BDD。


查看完整回答
反对 回复 2022-12-28
?
喵喔喔

TA贡献1735条经验 获得超5个赞

您的 NullPointerException 在存根期间被抛出,而不是在测试期间。

这是因为Matchers.any()实际上返回null,所以如果您在调用真正的方法时使用它,您将null作为参数传递。testMeString恰好有效,因为null + s不会导致 NullPointerException("null"改为使用字符串)。

代替:

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

你需要使用

doReturn("intercepted").when(blah).testMe(any());

这被记录为(虽然承认不是非常清楚)作为间谍真实物体的重要陷阱!在 Mockito 文档中。


查看完整回答
反对 回复 2022-12-28
  • 3 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信