zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    简谈单线程多线程的理解
    简谈vuex的理解
    简谈自己对redux的理解
    react-native-1
    react中信息传递的几种方式
    简谈对虚拟Dom的理解
    React-小总结
    移动端解决边框1像素问题
    JavaScript标记上的defer与async的作用与区别
    jQuery.smoove — jQuery和CSS3炫酷滚动页面内容元素动画特效插件
  • 原文地址:https://www.cnblogs.com/sl21100/p/5288058.html
Copyright © 2011-2022 走看看