mockito && powerMockito

区别:powerMockito可以mock类的静态方法,私有方法,私有成员变量。

1:mock类静态方法

@RunWith(PowerMockRunner.class)

@PrepareForTest(StaticClass.class)//含有静态方法的静态类

class PowerMockitoTest{

             @Test

            public void testXXX(){

                PowerMockito.mockStatic(StaticClass.class);

                PowerMockito.when(StaticClass.staticMethod()).thenReturn(new Object());

            }

}

2:mock私有方法

@RunWith(PowerMockRunner.class)

@PrepareForTest(PrivateClass.class)//含有私有方法的类

class PowerMockitoTest{

    @Test          

    public void testXXX(){           

            PrivateClass privateObject = PowerMockito.spy(new PrivateClass());                        PowerMockito.doReturn(new Object())

                   .when((privateObject,"privatemethodName",parameterList));       

     }

}

3:mock私有成员变量

@RunWith(PowerMockRunner.class)

@PrepareForTest(PrivateClass.class)//含有私有方法的类

class PowerMockitoTest{


        @Mock

        private PrivateField privateFiledObject;


        @Test

         public void testXXX(){

                PrivateClass privateObject = PowerMockito.spy(new PrivateClass());                       

                MemberModifier.field(PrivateClass.class,"privateField")

                                            .set(privateObject,privateFieldObject);

              }

}

你可能感兴趣的:(mockito && powerMockito)