【问题标题】:Mockito - stub abstract parent class methodMockito - 存根抽象父类方法
【发布时间】:2013-11-11 20:26:39
【问题描述】:

我看到一个非常奇怪的行为,试图对在抽象父类 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 只能存根在被模拟的类中定义的方法,而不是在超类中。

我正在阅读 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";
    }
}

班级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)

【问题讨论】:

  • 向我们展示堆栈跟踪
  • JB,我担心我不允许发布我的代码(我这样做是为了工作)。但也许我可以写一些类似的代码来重现这个问题
  • @JeffBowman 我在我的一个项目中复制了这个,没有使用 Proguard 或类似的东西。这真的很奇怪,在我看来就像 Mockito 中的一个错误。我正在使用 1.9.5。覆盖 DecryptedCard 中的存根方法(通过委托给超级实现)使测试通过。
  • 我想我知道为什么会这样。班级卡不公开。 Mockito 可能要求层次结构中的所有类都是公共的。如果我公开班级卡片,问题就会消失。
  • 这些 cmets 可能有一个很好的答案...

标签: java junit mockito


【解决方案1】:

根据this SO answer,当父类为非公开时,不能保证模拟行为,如issue 212 中所述。

(感谢 Brice 在另一个线程中的好答案,并感谢 Vladimir、JB Nizet 和 acdcjunior 在 cmets 线程中分享调试进度!)

【讨论】:

    【解决方案2】:

    哇!就是这样!

    我遇到了奇怪的异常:

    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"))
    

    虽然一切都是正确的。 我试图从模拟类的超类模拟方法,而这个超类与模拟类在同一个文件中,所以它不是公共的,并且会出现那些奇怪的错误。 将超类移动到单独的文件并将其设置为公开后,问题就消失了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多