PowerMock snippets

Mocking private methods:
• Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
• Use the @PrepareForTest(ClassWithPrivateMethod.class) annotation at the class- level of the test case.
• Use PowerMock.createPartialMock(ClassWithPrivateMethod.class, "nameOfTheMethodToMock") to create a mock object that onlymocks the method with name nameOfTheMethodToMock in this class (let's call it mockObject).
• Use PowerMock.expectPrivate(mockObject, "nameOfTheMethodToMock", argument1, argument2) to expect the method call tonameOfTheMethodToMock with arguments argument1 and argument2.
• Use PowerMock.replay(mockObject) to change the mock object to replay mode.
• Use PowerMock.verify(mockObject) to change the mock object to verify mode.


Mocking static methods:
• Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
• Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.
• Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.
• Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode.
• Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.


MockFinal:
• Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
• Use the @PrepareForTest(ClassWithFinal.class) annotation at the class-level of the test case.
• Use PowerMock.createMock(ClassWithFinal.class) to create a mock object for all methods of this class (let's call it mockObject).
• Use PowerMock.replay(mockObject) to change the mock object to replay mode.

• Use PowerMock.verify(mockObject) to change the mock object to verify mode.

No comments:

Post a Comment