1

I came across a scenario where I am not able to mock/stub a method.

Class A{
   B b = new B();
   method aa(){
   ... call to method bb in class B
 }
}
Class B{
   method bb(){
     ......
   }
}

I want to mock method bb for class B. Since method aa of class A doesn't have constructor where b is being passed I am not sure how I can mock it behavior.

I tried mocking B

A a = new A();
B b_mock = Mockito.mock(B.class);
when(b_mock.bb).thenReturn(..something);
a.aa();

But when testing method aa it still goes in method bb, which make sense as there is no relation between A and b_mock. I am not sure how to establish a connection between A and B.

I tried @InjectMock which also doesn't work and I am trying to avoid powerMock. I am not sure if this is achievable.

Thanks in advance!

Rishabh Agarwal
  • 2,374
  • 1
  • 21
  • 27
  • 1
    Are you able to refactor `A` to follow proper dependency injection? otherwise you would need to use PowerMock to mock the initialization of `B`, which while unfortunately possible, it encourages poor design with tight coupling. – Nkosi Oct 01 '18 at 00:09
  • I am trying to avoid power mock. I can do refactor, but by refactoring do you mean to make method aa as parameterized? if so, I won't be able to do that because it requires lots and lots of change for the current project – Rishabh Agarwal Oct 01 '18 at 00:15

1 Answers1

3

A is tightly coupled to B, which makes it difficult to unit test A in isolation.

If you are able to refactor A to follow explicit dependency principle via constructor injection

public class A{
    private B b;
    public A(B b) {
        this.b = b;
    }

    public void aa(){
        //... call to method bb in class B
    }
}

You would be able to inject the mock when testing

//Arrange
B b_mock = Mockito.mock(B.class);
A a = new A(b_mock);
when(b_mock.bb).thenReturn(..something);

//Act
a.aa();

//...

otherwise you would need to use PowerMock to mock the initialization of B, which while unfortunately possible, it encourages poor design with tight coupling.

Nkosi
  • 235,767
  • 35
  • 427
  • 472