How do you mock a final class with PowerMock?

2 Answers

  1. Use the @RunWith(PowerMockRunner. class) annotation at the class-level of the test case.
  2. Use the @PrepareForTest(ClassThatContainsStaticMethod. class) annotation at the class-level of the test case.
  3. Use PowerMock. mockStatic(ClassThatContainsStaticMethod. class) to mock all methods of this class.

How do you use PowerMockito mock static methods?

There are four easy steps in setting up a test that mocks a static call:

  1. Use the PowerMock JUnit runner: @RunWith(PowerMockRunner.
  2. Declare the test class that we’re mocking:
  3. Tell PowerMock the name of the class that contains static methods:
  4. Setup the expectations, telling PowerMock to expect a call to a static method:

Can a final class be mocked?

Configure Mockito for Final Methods and Classes Before we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

What is difference between mock and PowerMock?

Both tools are “hiding away” the collaborators in the class under test replacing them with mock objects. The division of work between the two is that Mockito is kind of good for all the standard cases while PowerMock is needed for the harder cases. That includes for example mocking static and private methods.

Why we should not use PowerMock?

Generally if you start new project and you (want to/ are forced) to use PowerMock because of the architecture of your code it means that this architecture is bad and needs improvement. Power Mock gives you access to mock static methods, constructors etc.

Can you mock final methods?

Configure Mockito for Final Methods and Classes Before Mockito can be used for mocking final classes and methods, it needs to be configured. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

How do you mock a class with a private constructor?

// Use the launcher of powermock @RunWith(PowerMockRunner. class) public class MyTestClass { @Test // Prepare the class for which we want to mock a static method @PrepareForTest(SiteUtil. class) public void myTest() throws Exception{ // Build the mock of Site Site mockSite = PowerMockito. mock(Site.