简体   繁体   English

Mockito 的 when() 不存根超类的方法

[英]Mockito's when() isn't stubbing superclass's method

I have 'MyClass' inheriting from 'BaseClass' with a method doBaseStuff() that isn't overloaded:我有一个从 'BaseClass' 继承的 'MyClass' 方法doBaseStuff()没有重载:

public class BaseClass {
    public String doBaseStuff(String var1, String var2) {
        //Do something
        return someStringValue;
    }

public class MyClass extends BaseClass {
    public String doMyStuff(String var1, String var2) {
        //Do some stuffs
        doBaseStuff(var1, var2);
        //Do more stuffs
        return someStringValue;
    }
}

Then I have a test case for MyClass :然后我有一个MyClass的测试用例:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

    @InjectMocks
    MyClass myClass;

    public void testDoOtherThing() {
        // Some setups
        when(myClass.doBaseStuff(dummyVar1, dummyVar2))
                .thenReturn("This isn't catching the invocation!");

        myClass.doMyStuff(dummyVar1, dummyVar2);

        // Some verify statements
    }
}

However, when / then statement for doBaseStuff() is not mocking the behaviour whenever that method is invoked.但是,无论何时调用该方法, doBaseStuff() when / then语句都不会doBaseStuff()行为。

As a (very shitty) workaround, I can declare a separate BaseClass object as a member of MyClass :作为(非常糟糕的)解决方法,我可以声明一个单独的BaseClass对象作为MyClass的成员:

public class MyClass extends BaseClass {
    private Baseclass baseClass;

    ...

         baseClass.doBaseStuff(var1, var2);

    ...

}

public class MyClassTest {
    @InjectMocks
    MyClass myClass;
    @Mock
    BaseClass baseClass;

    ...

    when(baseClass.doBaseStuff(dummyVar1, dummyVar2))
            .thenReturn("This technically works, but ugh...");

    ...

}

However, MyClass one of the subclasses of BaseClass shares common functionality.但是,作为BaseClass的子类之一的MyClass共享通用功能。

Is there any way for MyClass mock to be aware of doBaseStuff() implementation? MyClass模拟有什么方法可以知道doBaseStuff()实现吗?

You want to use @Spy instead:你想改用@Spy

@Spy
MyClass myClass;

The difference between a mock and a spy is well answered here .模拟和间谍之间的区别在这里得到了很好的回答。

Also, when().thenReturn() method will acually execute the real method.此外, when().thenReturn()方法将实际执行真正的方法。 Only the return value is substituted.仅替换返回值。 If you don't want to execute the original method, use doReturn().when() syntax instead:如果不想执行原始方法,请改用doReturn().when()语法:

doReturn("This technically works, but ugh...").when(myClass).doBaseStuff(dummyVar1, dummyVar2);

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

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