[JAVA] Mock and spy on PowerMock

table of contents

  1. Procedure for building an environment for using PowerMock
  2. Mock and spy on PowerMock ← Now here
  3. Mock static methods with PowerMock
  4. Mock the constructor with PowerMock
  5. Mock private methods with PowerMock
  6. Try using WhiteBox of PowerMock
  7. Disable static initializer in PowerMock

Overview

In order to set arbitrary behavior with static method and private method in PowerMock, it is first necessary to mock / spy the target class.

Here, it is assumed that the Utility class will be mocked / spyed.

Utility.java


public class Utility {
	//The contents are omitted. anything is fine.
}

Mocking

Mocking in PowerMock, like Mockito, is used to arbitrarily define the behavior of a method for the convenience of unit tests. You can also record and verify the number of calls.

Immediately after mocking, the mock object is in a state where the behavior of the method is not defined, so use it by defining a return value or exception with doReturn or doThrow. (* Methods that do not define behavior return null as a return value.)

To mock, pass the Class of the class you want to mock to the argument of PowerMockito.mock.

Utility mock = PowerMockito.mock(Utility.class);

Spy

Unlike mocking, spying is used when you want to define arbitrary behavior for some methods.

Immediately after spying, the Utility class behaves just like an instance of a regular Utility class. (Recording and verification of the number of calls is possible.)

In other words, it works in the same way as a normal method, except for methods that set arbitrary behaviors and exceptions with doReturn, doThrow, etc.

To spy, pass an instance of the class you want to mock in the PowerMockito.spy argument.

Utility spy = PowerMockito.spy(new Utility());

Recommended Posts

Mock and spy on PowerMock
Mock Enums with PowerMock
Mock static methods with PowerMock
Mock and stub in RSpec
Mock the constructor with PowerMock
Enable Openjdk10 and maven on CentOS
Install JDK and JRE on Ubuntu 16.10
Install and configure jenv on macOS
Proper use of Mockito and PowerMock
Enable Java 8 and Java 11 SDKs on Ubuntu
Notes on Java path and Package
Install Java 9 on windows 10 and CentOS 7
Installing and using Ansible on Ubuntu 16.04