Jyoti Yadav
Jyoti Yadav

Reputation: 106

How to mock chained dependencies in Java using Mockito

I have Class A, which has a dependency on class B. And class B has again has a dependency on class C. Structure looks like:

Class A(){
    @Autowired
    private B b;

    public void someMethod(){
        b.callAnotherMethodAndGetValue();
    }
}

Class B(){
    @Autowired
    private C c;

    public void callAnotherMethodAndGetValue(){
        c.callAnother();
    }
}

Class ATest(){
    @Spy
    private B b;

    public void someMethod(){
        // it goes into this method, and throws null pointer exception at
        // c.callAnother(); as c is null.
        b.callAnotherMethodAndGetValue();
    }
}

Is there any way I can let the stack flow to c.callAnother from Test Cases. Without doing when then at b.callAnotherMethodAndGetValue();

Upvotes: 1

Views: 464

Answers (1)

Timothy Truckle
Timothy Truckle

Reputation: 15622

You need to mock C: and not spy on b:

@Mock
C c;

@InjectMocks
B b;
@Test
public void someMethod(){
  b.callAnotherMethodAndGetValue();
}

Off cause you'd make your life easier if you used constructor injection!


I am writing the test cases for Class A. Inside Test For Class A , I should do @InjectMocks A a and should do a.someMethod() – Jyoti Yadav

Then the test should look like this:

@Mock
B b;

@InjectMocks
A a;

@Test
public void someMethod(){
  a.someMethod();
}

Upvotes: 5

Related Questions