用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方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM