简体   繁体   English

使用通用方法的Mockito

[英]Mockito with generic method

I am trying to mock a generic method on my class with mockito but when the test code runs i always get a NullPointerException. 我正在尝试使用Mockito在类上模拟通用方法,但是当测试代码运行时,我总是会收到NullPointerException。

This is the class i want to mock. 这是我要模拟的课程。

public abstract class MyClass{
      public abstract <T> T find(T t);
}

My test code looks something like this. 我的测试代码看起来像这样。

@Mock private MyClass myClass;

public testOnReceive(){
             Mockito.when(
                myClass.find(Mockito.isA(BroadcastReceiver.class))).
                thenReturn(broadcastReceiver);

                myReceiver.onReceive(context,intent);

}

And finally the class i am trying to test is an extention of the BroadcastReceiver class and this is the code that i want to test 最后,我要测试的类是BroadcastReceiver类的扩展,这是我要测试的代码

public class MyReceiver extendes BroadcastReceiver{
       public onReceive(Context context , Intent intent){
             ...
             ...
             myClass.find(this);
       }
}

The problem is with the mocking of the class. 问题在于类的嘲笑。 The class actually gets mocked(it is not null) but when the generic method is called then i get a null. 该类实际上被嘲笑(它不是null),但是当泛型方法被调用时,我得到的是null。

Any ideas? 有任何想法吗?

Thank you 谢谢

Here is a solution which should work for you, even if you have partial mocking (ie for some methods you want the real method to be invoked while sometimes you want the mock): 即使您有部分模拟,也可以使用以下解决方案(例如,对于某些方法,您希望真正的方法被调用,而有时您希望模拟):

public class AbstractMethodMocker implements Answer<Object> {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable
    {
        Answer<Object> answer;
        if (isAbstract(invocation.getMethod().getModifiers()))
            answer = RETURNS_DEFAULTS;
        else
            answer = CALLS_REAL_METHODS;
        return answer.answer(invocation);
    }
}

@Test
public void testOnReceive() {
    MyClass clazz = mock(MyClass.class, new AbstractMethodMocker());
    when(clazz.find(any(BroadcastReceiver.class)).thenReturn(broadcastReceiver);
    myReceiver.onReceive(context, intent);
}

Here is a great blog which discusses strategies of dealing with abstract classes (and their methods) using the Mockito framework. 这是一个很棒的博客 ,讨论了使用Mockito框架处理抽象类(及其方法)的策略。

My solution is similar to what Tim suggested but using a different kind of Answer object. 我的解决方案与Tim所建议的类似,但是使用了另一种类型的Answer对象。 Although i don't completely understand why but what worked for me was the following. 虽然我不完全理解为什么,但是以下对我有用的是。

MyClass myClass = Mockito.mock(MyClass.class , Mockito.RETURNS_DEEP_STUBS);

After that i did not need to specify anything about when the method is called. 之后,我无需指定有关何时调用该方法的任何信息。

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

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