Mockito Mock static method

In this post, we will see about Mockito Mock static method.

If you want to mock static methods, you need to use PowerMockito.PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.
Let’s create a simple example to mock static method using powermockito.

1. Create a simple java maven project.

2. Adding Dependencies with Maven

Let’s add PowerMock dependencies to our maven project.

Your pom.xml will look like below:

Now that we are done adding dependencies, let’s enable the use of annotations in our tests.

3. Enabling PowerMock Annotations

Just like what we need to do with Mockito, we also need to enable the use of Annotations with PowerMockito. Much like Mockito, we make use of similar annotations, as shown:

Let us look at each annotation we used above:

  • @RunWith annotation is similar to what we did in Mockito. Instead of using Mockito, we will use a PowerMockRunner this time, which will enable PowerMockito APIs in the test.
  • @PrepareForTest informs PowerMockito which classes to prepare with Java Reflection API for testing.

 4. Create class with static method

create a class named StringUtil. This is the class under test. It has one static method named checkSubString(). We are going to mock this checkSubString() using PowerMockito.

 5. Create test class to mock static method

Create class named PowerMockStaticMethodTest to mock static method

Let go through each step one by one:

  1. We defined a boolean expection to true.
  2. Another generic String message, to be used as an expectation.
  3. Prepare StringUtil for static method test.
  4. Setting expection when static method checkSubString() is going to get called
  5. Invoking the static method.
  6. Verifying the expected and actual result.

 6. Run the test

When you run above test, you will get below output:
PowerMock test result
That’s all about Mockito mock static method.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *