zoukankan      html  css  js  c++  java
  • 用PowerMock mock static方法

    在编写代码时,经常需要调用别人已经写好的工具类,而这些工具提供的方法经常是static方法,在这里,直接贴出《PowerMock实战手册》中的例子

    待测试方法:

    public class EmployeeService {
        public int getEmployeeCountWithStatic() {
            return EmployeeUtils.getEmployeeCount();
        }
    }

    引用的工具类

    public class EmployeeUtils {
        public static int getEmployeeCount() {
            throw new UnsupportedOperationException();
        }
    }

    测试方法:

    @PrepareForTest(EmployeeUtils.class)
    public class EmployeeServiceTestWithStaticTest   extends PowerMockTestCase{
        
        private EmployeeService employeeService;
        
        @ObjectFactory
        public ITestObjectFactory getObjectFactory() {
            return new PowerMockObjectFactory();
        }
        
        @BeforeMethod
        public void init(){
             employeeService = new EmployeeService();
        }
    
        @Test
        public void testGetEmployeeCountWithStatic() {
            PowerMockito.mockStatic(EmployeeUtils.class);
            PowerMockito.when(EmployeeUtils.getEmployeeCount()).thenReturn(10);
            int count = employeeService.getEmployeeCountWithStatic();
            Assert.assertEquals(10, count);
        }
    }

    重点是

    PowerMockito.mockStatic(EmployeeUtils.class);

    mock类EmployeeUtils中的所有static方法

  • 相关阅读:
    指针的学习
    (转)c & c++内存分配
    C++实现String
    c& c++笔试题
    appium python api收集
    公司python入职培训流程
    app端性能测试笔记
    h5 测试关注点
    robot framework 牛刀一试
    adb 安装apk 报错:Failure [INSTALL_FAILED_INVALID_URI]
  • 原文地址:https://www.cnblogs.com/changzhz/p/5162295.html
Copyright © 2011-2022 走看看