如何使用powermock编写静态方法的测试用例

时间:2014-03-17 16:06:50

标签: easymock powermock testcase

如何为此编写测试用例?

Class ClassToBeTested{

    Result method(){
        //static method called here
        session session=ClassContainsStatic.staticMethod();

        //method called here
        Query query=session.createQuery();

        //method returned here
        return query.uniqueResult();
    }
}

1 个答案:

答案 0 :(得分:0)

请按以下步骤操作:

  1. 在测试用例的类级别使用@RunWith(PowerMockRunner.class)注释。
  2. 在测试用例的类级别使用@PrepareForTest(ClassThatContainsStaticMethod.class)注释。
  3. 使用PowerMock.mockStatic(ClassThatContainsStaticMethod.class)来模拟此类的所有方法。
  4. 使用PowerMock.replay(ClassThatContainsStaticMethod.class)将类更改为重播模式。
  5. 使用PowerMock.verify(ClassThatContainsStaticMethod.class)将类更改为验证模式。
  6. 参考:https://code.google.com/p/powermock/wiki/MockStatic