Mocking a Private Variable that is Assumed to Exist

前端 未结 2 2019
日久生厌
日久生厌 2021-02-12 10:25

How can you get a mock object in at runtime when it is not created/initialized in the class you are testing, it is not static (singleton pattern), or you don\'t have some sort o

2条回答
  •  旧时难觅i
    2021-02-12 11:22

    Several approaches here:

    1. ReflectionTestUtils of Spring Testing framework: ReflectionTestUtils.setField(objectToTest, "privateFieldName", mockObjectToInject);. With this you don't introduce another dependency.
    2. org.mockito.internal.util.reflection.FieldSetter.
    3. PowerMock.Whitebox.setInternalState() to mock a private field.

    If you need to mock internal local variable creation, use PowerMockito.whenNew(Foo.class).withNoArguments().thenReturn(foo);. Very, very useful. Cannot find other ways to do the same.

    With only Mockito you cannot mock local variable creation, because when(any(Foo.class) does not work; will return null. It compiles but does not work.

    References: Mockito: Mock private field initialization

提交回复
热议问题