Search code examples
javaunit-testingmockitopowermockpowermockito

mock a public method of other class in a method (java)


I am new to Mockito. For the code:

public class A{
   public A{
      ...
      B.fff();  //the function I want to mock
      ...
   }
}

public class B{
    public boolean fff(){
       ...
       ...  //connect DB
       ... 
    }
}

For the unit test,

public class ATest{

    @Test
    public void test(){
        A mock_a = new A();
        Assert.assertNotNull(mock_a);
    }
}

Because of the function "B.fff()" need connect the DB,so I would like to mock the function "B.fff()" with return true or false for let the test can work completely without environment.

I tried some code like:

public class ATest{

    @Test
    public void test(){
        PowerMockito.when(B.fff()).thenReturn(true);
        Assert.assertNotNull(new A());
    }
}

but it isn't working.

Is there any solution by using Mockito(or PowerMock)?

Thanks.


Solution

  • What you actually want to do here is inject a mock of B into A. Long term that will require setting up an inversion of control container, but if this is a simple test app you can start with (pseudo code here ... I'm typing this on my phone):

    Public class A{
      Public A(B bInstance){
        This.b = bInstance;
      }
      Public void foo() {
        B.doSomethingWithDb();
      }
    }
    

    In your test, you will mock B and set up your expected return value, then inject that into your constructor of A.

    Do some reading on IOC - it will make your testing much easier and will make you a better programmer in the long run.