-1

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.

  • Possible duplicate of [How to mock local function in a function java](https://stackoverflow.com/questions/45293836/how-to-mock-local-function-in-a-function-java) – shmosel Jul 26 '17 at 03:11

1 Answers1

1

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.