简体   繁体   中英

NullPointerException in super class method's constructor when testing using mockito

I have a super class:

public class A extends Fragment{
    public A(Context context){
        super(context);
    }
}

and class B inherits it:

public class B extends A{
    public B(Context context){
        super(context);
    }
}

In my test class where I'm using Robolectric and Mockito, when I instantiate class B like so: B b = new B(context)

I get a nullpointerexception in class A's constructor's super method. Am I doing something wrong?

Here's the test code:

@Mock Context context;
@Before
public void setup() {
    initMocks(this);

    B b = new B(context);
}

Simple answer: it isn't that easy.

The exception stack trace which you are hiding from us would tell you/us that those NPE happens within some base Android code. Thing is: you are passing a context object into the Fragment constructor.

Guess what: the Fragment code then starts using that context object. It makes a whole series of calls on that object, in order to retrieve other objects, to then make calls on those objects.

Right now, you only mocked a Context object. Any calls to it that are supposed to return a value will return null by default. Mockito doesn't know anything about the classes you are mocking. So, when you want that a certain call returns something else than null, you have to specify that behavior.

So, the "short" answer is: you have to prepare that mock object to be able to be used like this. The long answer ... was already given; and you need to study its details in depth!

Beyond that; you can have a look into another question dealing with the exact same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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