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

标签 java testing mockito spy

我有一个 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 方法进行 stub 和测试。请注意,我只是想了解 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)。

最佳答案

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

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

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

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

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

除了这个问题,我认为你不需要任何 spy 来测试这个方法。
spy 是一种非常特殊的模拟工具,仅当您别无选择时才使用它:您需要模拟被测对象,这是一种不好的做法,并且您无法重构实际代码。

但是在这里你可以这样做:

@Test
public void testTestMe(){
    Blah blah = new Blah();
    ArrayList<String> l = new ArrayList<String>();
    l.add("oopsie");
    assertEquals("hello oopsie",blah.testMe(l));
 }

关于java - 使用 any() 或 anyList() 时,使用 ArrayList/List 参数清除方法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56400310/

相关文章:

java - 如何从 Spring MVC 登录

testing - Cucumber Feature 文件看不到 "step"文件

asp.net-mvc-3 - 使用序列化 View 结果的 mvc3 单元测试最佳实践

Java Mockito : Test a protected abstract method

java - 我应该模拟我的测试对象与之交互的所有对象吗?

java - 如何在Java Map中进行for循环检查并在if语句后将值设置为假?

java - 无法从我的数据库中获取信息

python - nosetest 的设置方法。 (测试类)

java - Mockito @InjectMocks 不适用于相同类型的字段

java - Android/Java - 随机读取行没有改变