AgentX
AgentX

Reputation: 1462

Mockito - mock a method call in constructor

I have a class X which takes in a YBuilder and constructs an instance of Y

public class X {
  private Y y;
  public X(YBuilder builder) throws IOException{
    y = builder.build();
  }
}

I need to mock all calls to Y, so I have written my Unit tests like this:

@Mock
private Y Y;

@Mock
private YBuilder builder;

@InjectMocks
private X x;

@Before
public void setup() {
  when(builder.build()).thenReturn(y); // this does not work
}

I get a Null Pointer Exception in my main class since the dependency Y has not been mocked.

I think this is due to the fact that @InjectMocks instantiates a new instance of X before I am able to mock the call.

How can I fix this? Any inputs are appreciated.

Upvotes: 0

Views: 3722

Answers (2)

vikingsteve
vikingsteve

Reputation: 40388

Right, ok - the issue here is that the code y = builder.build() is called in the constructor of X, before when(builder.build()).thenReturn(y) is ever set up.

Do you have control over class X? If so, are you able to store a reference to the builder in X, and call .build() later?

public class X {
    private YBuilder builder;
    public X(YBuilder builder) {
        this.builder = builder;
    }
}

Otherwise it might be most straightforward to initialize the mocks manually in the setup() method.

Upvotes: 1

Ken Brittain
Ken Brittain

Reputation: 2265

If you think something is happening then prove it with the code. You can remove the observed behavior and construct X yourself:

@Before
public void setup() {
  when(builder.build()).thenReturn(y); // this does not work
  x = new X(builder);
}

If this works then you have validated your concern and can move on in your testing.

Upvotes: 0

Related Questions