Mock利器:PowerMock

powerMock不仅支持接口mock,final类、静态类、静态方法、私有方法都支持mock,还是很强大的;

1.gradle引用:

myonlycompile('org.powermock:powermock-module-junit4:1.6.4')
myonlycompile('org.powermock:powermock-api-mockito:1.6.4')

 

2.测试代码

@RunWith(PowerMockRunner.class)
@PrepareForTest(mockTest.FinalUser.class)
public class mockTest {
    @Test
    public void testMockInterface() {
        IService svc = PowerMockito.mock(IService.class);
        PowerMockito.when(svc.getMsg("aa")).thenReturn("my name is aa");

        assertEquals("my name is aa", svc.getMsg("aa"));
    }

    @Test
    public void testMockClass() {
        User user = PowerMockito.mock(User.class);
        PowerMockito.when(user.getCount()).thenReturn(5);
        assertEquals(5, user.getCount());
    }

    @Test
    public void testMockFinalClass() {
        FinalUser user = PowerMockito.mock(FinalUser.class);
        PowerMockito.when(user.getCount()).thenReturn(5);
        assertEquals(5, user.getCount());

        PowerMockito.when(user.getNum()).thenReturn(8);
        assertEquals(8, user.getNum());
    }

    @Test
    public void testMockStaticClass() {
        PowerMockito.mockStatic(FinalUser.class);
        PowerMockito.when(FinalUser.getName()).thenReturn("MY");
        assertEquals("MY", FinalUser.getName());
    }

    static interface IService {
        String getMsg(String msg);

        void addMsg(String msg);
    }

    static class User {
        private String name;

        public int getCount() {
            throw new NotImplementedException();
        }
    }

    static final class FinalUser {
        private String name;

        public static String getName() {
            throw new NotImplementedException();
        }

        public int getCount() {
            throw new NotImplementedException();
        }

        private int getNum(){
            throw new NotImplementedException();
        }
    }
}

 

如果是静态类、方法、final类、私有方法的需要加上

@RunWith(PowerMockRunner.class)
@PrepareForTest(mockTest.FinalUser.class)

posted @ 2016-03-17 16:52  sl521100  阅读(752)  评论(0编辑  收藏  举报