Tejas Shah
Tejas Shah

Reputation: 571

how to mock method from calling class using mockito in java

I have a class that calls method from another class to get the report status.

Class A {
  private classb b = new classb();
  method x() {
    String xyz =b.method1( parm1, parm2) 
  }
}

So, when for Junit test for method x getting null pointer on b.method(). I have created mock for class b and did following

Mockito.doReturn(val).when(classbMock).method1(parm1,parm2);

Please help how can I mock the class b and get pass it.

Thanks

Upvotes: 2

Views: 4460

Answers (2)

Jeff Foster
Jeff Foster

Reputation: 44696

In order to mock b you'll need to give it to the instance of class A.

There's at least several ways of doing this:

  1. Use something like ReflectionUtils to poke around in A and change the value of the field
  2. Give A a constructor that allows you to inject the dependency into A
  3. Just mock A.x and assume that b works (because that has it's own unit test)

I'd prefer option 3 (assuming that A is a dependent of the thing under test and not the thing being tested). For a unit test I only want to mock the immediate dependencies, not all of the transient dependencies.

Upvotes: 2

matt b
matt b

Reputation: 139921

Instead of ClassA instantiating it's own instance of ClassB, pass the instance of B in via A's constructor (or a setter):

public class ClassA {
     public ClassA(ClassB b) {
          this.b = b;
     }
     public void x() {
          String blah = b.method1(parm1, parm2);
     }
}

Then in your test, you can pass the mock version of B to the instance of A being tested:

ClassB classBMock = mock(ClassB.class);
ClassA a = new ClassA(classBMock);

And your real code can pass in the non-mock version of ClassB to A.

Upvotes: 0

Related Questions