2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I disagree with 3 - in the unit test of A you want to test what A.x() does with the return value of b.method1(), and what it in turn returns - assuming that the example code above is just very simplified (and that in the real world it wouldn't be calling a method and doing nothing with the response)
Maybe I didn't read things right, but I was imagining there's a class C that we can't see that's under test. It has a dependency on A. In that case, I wouldn't want to be mocking out A's dependants, I'd just want to mock A. I think that's a long winded saying of I agree with you.
Yeah we do agree :) I interpreted the question as writing a test for A
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.