How to mock external dependencies for final objects?

走远了吗. 提交于 2021-01-28 12:31:43

问题


public class A{
   private final B b;
   public void meth() {
      //Some code
      Integer a = b.some_method(a,fun(b));
      //Some code
   }
   private fun(int b) {
     return b;
   }
}
 when(b.some_method(anyInt(),anyInt())).thenReturn(100)

How to mock the externally dependency when writing unit tests for class A. When i mock dependency in the above way, the value of "a" is not getting assigned to 100 as expected.


回答1:


Actually the answer of Jakub is correct. Maybe you need an example to understand how to do it. Check the main method and the contructor of my example.

public class A {
    private final B b;

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

    public void meth() {
        //Some code
        Integer a = b.some_method(5,fun(5));
        //Some code
        System.out.println(a);
    }
    private int fun(int b) {
        return b;
    }

    public static void main(String[] args) {
        B b = Mockito.mock(B.class);

        when(b.some_method(anyInt(), anyInt())).thenReturn(100);

        new A(b).meth();
    }

}

With the constructor you have to set B with your mock (see the last third line in the main method). When you run the main method you will see the output of the System.out and it is 100.




回答2:


You can use powermock library to mock final object. This is the implementation from their wiki.

Testing class:

public class StateFormatter {

private final StateHolder stateHolder;

public StateFormatter(StateHolder stateHolder) {
    this.stateHolder = stateHolder;
}

public String getFormattedState() {
    String safeState = "State information is missing";
    final String actualState = stateHolder.getState();
    if (actualState != null) {
        safeState = actualState;
    }
    return safeState;
 }
}

Test snippet:

StateHolder stateHolderMock = createMock(StateHolder.class);
StateFormatter tested = new StateFormatter(stateHolderMock);

expect(stateHolderMock.getState()).andReturn(expectedState);

        // PowerMock.replay(..) must be used. 
replay(stateHolderMock);

You can find full sample here.

  1. You have to change your constructor in class A to parameterized.
  2. Create a object by passing mock object B created using powermock


来源:https://stackoverflow.com/questions/45308286/how-to-mock-external-dependencies-for-final-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!