0

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);
}
syfy
  • 607
  • 3
  • 12
  • 19

1 Answers1

2

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.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Is the mock object in this case supposed to be the super class? – syfy May 08 '17 at 06:29
  • You can't mock the super **class**. You mock **objects**. This reads like you are overburdening yourself. Thing is: mocking Android stuff is a whole lot "different" than doing "normal" java unit testing an mocking. Thus: please read that link I provided. Read it until you understand it! – GhostCat May 08 '17 at 06:30
  • Um okay. Which object would you want me to mock in this case? It can't be the class under test, and I'm already mocking context. – syfy May 08 '17 at 06:33
  • I enhanced my answer and added another link to a similar problem. Maybe my other answer there helps more. The point is: you have to check the exception stack trace, and then you have to **mock** all those requests on that context object that will be coming in when super(context) is executed. But I am pretty sure that there are existing frameworks to do that for you. You dont want to go in and re-invent the wheel here. – GhostCat May 08 '17 at 08:38