Mockito - 桩设抽象父类方法

4
我发现在尝试为定义在抽象父类MyAbstractBaseClass中的类MyClass中的方法myMethod(param)设置存根时,出现了非常奇怪的行为。
当我尝试使用doReturn("...").when(MyClassMock).myMethod(...)等来设置存根时,该方法失败,并且在不同的情况下抛出不同的异常。这些异常会直接抛出在那一行代码上。
当我使用doReturn("...").when(MyClassMock).myMethod(CONCRETE PARAM CLASS OBJECT)时,我会得到以下异常:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
String cannot be returned by hasValidExpirationDate()
hasValidExpirationDate() should return boolean
    at ...

hasValidExpirationDate()并不是一个被存根的方法,但它被抽象基类中MyMethod(param)的真实实现调用。

当我使用doReturn("...").when(MyClassMock).myMethod(any(PARAMCLASS.class))时,我会得到以下异常:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded.
This exception may occur if matchers are combined with raw values:

但是当我在子类MyClass中定义方法myMethod(param)时,代码不再失败。我在MyClass中的具体实现只是调用super.myMethod(param)并返回它,因此它除了修复单元测试外没有任何效果。所以看起来Mockito只能存根(mock)被mock的类中定义的方法,而不能存根它的超类中的方法。
我正在阅读Mockito文档,但我没有找到它说不能存根继承方法的地方。
myMethod(param)既不是static也不是final。
代码:
类BaseCard:
import java.io.Serializable;

public class BaseCard implements Serializable {

    public boolean hasValidExpirationDate() {
        return true;
    }
}

Card类:

abstract class Card  extends BaseCard {

    public Card () {    }

    public String getUnexpiredStringForNetwork(){

        //If the date is invalid return empty string, except for Discover.
        if( ! hasValidExpirationDate()){
           return "hi";
        }

        return "hello";
    }
}

Class DecryptedCard:

public class DecryptedCard extends Card {

}

MyTest:

import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

import org.junit.Test;


public class MyTest {

    @Test
    public void test() {
        DecryptedCard decryptedCardMock = mock(DecryptedCard.class);

        doReturn("ABC").when(decryptedCardMock).getUnexpiredStringForNetwork();

    }

}

失败:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
String cannot be returned by hasValidExpirationDate()
hasValidExpirationDate() should return boolean
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

    at Card.getUnexpiredStringForNetwork(Card.java:10)
    at DecryptedCard.getUnexpiredStringForNetwork(DecryptedCard.java:1)
    at MyTest.test(MyTest.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

1
请展示堆栈跟踪。 - Philipp Sander
1
JB,我很抱歉,我不被允许发布我的代码(因为这是我的工作)。但也许我可以编写一些类似的代码来重现这个问题。 - Vladimir Makhnovsky
2
@JeffBowman,我在我的一个项目中重现了这个问题,没有使用Proguard或其他类似的东西。这真的很奇怪,看起来像是Mockito的一个bug。我正在使用1.9.5版本。通过委托给super实现来覆盖DecryptedCard中已存根方法可以使测试通过。 - JB Nizet
1
我想我知道为什么会发生这种情况。类Card不是公共的。Mockito可能要求层次结构中的所有类都是公共的。如果我将类Card设为public,问题就解决了。 - Vladimir Makhnovsky
1
这些评论中可能有一个好的答案... - vikingsteve
显示剩余10条评论
2个回答

1
根据此SO答案,当父类为非公共类时,模拟行为并不保证有效,正如问题212中所述。
(感谢Brice在另一个帖子中的好回答,以及Vladimir、JB Nizet和acdcjunior在评论线程中分享调试进度!)

0

哇!就是这样!

我一直在遇到奇怪的异常:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected here:

-> at com.medziku.motoresponder.logic.ExposedResponder.createSettings(ResponderTest.java:163)
-> at com.medziku.motoresponder.logic.ExposedResponder.createSettings(ResponderTest.java:163)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

虽然一切都是正确的。 我试图从模拟类的超类中模拟方法,而这个超类在同一个文件中作为模拟类,因此它不是公共的,导致了那些奇怪的错误。 将超类移动到单独的文件中,并将其设置为公共的后,问题就解决了!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接