简体   繁体   English

Mockito - 模拟子类方法调用

[英]Mockito - mock subclass method call

I am working with legacy code and trying to write a unit test for an implementation I did. 我正在使用遗留代码并尝试为我执行的实现编写单元测试。 I have the following structure: 我有以下结构:

   AbstractClass:
    ----------------

    public AbstractClass {

    abstract method2();

     void method1(){   
      ...does something...
      ..calls --> method2()
     }
    }

    Subclass
    ------------
    public Subclass extends AbstractClass(){

     void method2(){
      ..do something....
      ..mockThisMethod()...

       return true;   
     }
 }

I have an abstract class which has some logic implemented in a specific method. 我有一个抽象类,它有一些在特定方法中实现的逻辑。 This method calls than another method implemented in the subclass. 此方法调用比子类中实现的另一个方法。 The method in the subclass calls other methods which I want to mock. 子类中的方法调用我想要模拟的其他方法。

Is this possible without changing the implementation code (hard to change)? 这是否可以在不改变实施代码的情况下进行(难以改变)? Mos of the results are suggesting using mockito spying but it doesn't work. 结果的Mos建议使用mockito间谍,但它不起作用。

I followed the TestDesign describer here: 我在这里关注了TestDesign描述符:

https://www.tildedave.com/2011/03/06/pattern-stubbing-legacy-superclasses-with-mockito-spies.html https://www.tildedave.com/2011/03/06/pattern-stubbing-legacy-superclasses-with-mockito-spies.html

What I did is: 我做的是:

 Subclass subclass= spy(Subclass.class);
 when(subclass.mockThisMethod()).thenReturn(something);
 subclass.method1() (I am not sure if this line is correct?)

So what I want to avoid is, calling the method ( mockThisMethod ) in the Subclass . 所以我想避免的是,调用Subclass的方法( mockThisMethod )。 Since this method does some db-stuff an so on. 因为这个方法做了一些db-stuff等等。 I know it would be easier to test, if I use object composition instead of inheritance but at this point, it is hard to change the whole implementation. 我知道测试会更容易,如果我使用对象组合而不是继承,但在这一点上,很难改变整个实现。 The code above is not working..I get a NPE. 上面的代码不起作用..我得到一个NPE。

1) You do not create a Spy by passing the class to the static Mockito.spy method. 1)您不通过将类传递给静态Mockito.spy方法来创建Spy。 Instead, you must pass an instance of that particular class: 相反,您必须传递该特定类的实例:

Subclass subclassSpy = spy(new Subclass());

Also, consider using annotations: 另外,请考虑使用注释:

@Spy
private Subclass subclassSpy = new Sublcass();

@Before
public void init(){
   MockitoAnnotations.initMocks(this);
}

2) Avoid using when.thenReturn when stubbing a spy. 2)避免使用when.thenReturnwhen.thenReturn间谍时返回。 Instead, use doReturn..when..methodCall : 相反,使用doReturn..when..methodCall

doReturn(something).when(sublcass).mockThisMethod(); 

otherwise you will invoke the actual method while stubbing and this may lead to unwanted behavior and/or exceptions. 否则你将在存根时调用实际方法,这可能会导致不必要的行为和/或异常。

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

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