[JAVA] Mockito + PowerMock cheat sheet

Introduction

When mocking with Mockito + PowerMock in Java unit tests, try to summarize the ones you are likely to use as briefly as possible. (I plan to add it as needed)

table of contents

-[Introduce Mockito and PowerMock](Introduce #Mockito and PowerMock) --[Mock static method](Mock #static method) --[Mock a new instance](Mock a #new instance) -[Mock some methods](#Mock some methods)

Introduce Mockito and PowerMock

For Gradle, add the following dependency to build.gradle.

build.gradle


dependencies {
    testImplementation 'junit:junit:4.12'
    testImplementation "org.mockito:mockito-core:2.28.+"
    testImplementation 'org.powermock:powermock-module-junit4:2.0.2'
    testImplementation 'org.powermock:powermock-api-mockito2:2.0.2'
}

Mock static methods

Let's mock the static method "ExampleDBA.findAll ()" called from the method when testing the following method.

Tested class


import java.util.List;

public class ExampleLogic {
    public Integer countExamples() {
        List<ExampleDTO> list = ExampleDBA.findAll();
        return list.size();
    }
}

Test class


import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.when;

import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class) //(1)
@PrepareForTest({ ExampleDBA.class }) //(2)
public class ExampleLogicTest {

    ExampleLogic logic = new ExampleLogic();

    @Before
    public void setUp() throws Exception {
        PowerMockito.mockStatic(ExampleDBA.class); //(3)
    }

    @Test
    public void countExamples() {
        List<ExampleDTO> result = Arrays.asList(new ExampleDTO());
        when(ExampleDBA.findAll()).thenReturn(result); //(4)
        assertThat(logic.countExamples(), equalTo(1));
    }
}

(1) This is a magical trick required when using PowerMock. (2) Specify a class that has a static method to mock. (3) Specify a class that has a static method to mock. (4) Specify the return value when the static method is executed.

Mock a new instance

Tested class


public class ExampleService {
    public Integer count() {
        ExampleLogic logic = new ExampleLogic();
        return logic.countExamples();
    }
}

Test class


import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class) //(1)
@PrepareForTest({ ExampleService.class }) //(2)
public class ExampleServiceTest {

    ExampleService service = new ExampleService(); //(3)

    @Test
    public void count() throws Exception {
        ExampleLogic logic = mock(ExampleLogic.class); //(4)
        whenNew(ExampleLogic.class).withNoArguments().thenReturn(logic); //(5)
        when(logic.countExamples()).thenReturn(0); //(6)

        assertThat(service.count(), equalTo(0));
    }
}

(1) This is a magical trick required when using PowerMock. (2) Specify the class to be tested. (3) Create an instance of the class to be tested. (4) Create a mock object. (5) Set to return a mock object when new. (6) Set the return value when the mock object method is called. (*) It is necessary to execute (4) to (6) before newing the object to be mocked. For example, if you are newing ExampleLogic in the constructor of ExampleService ExampleService must be (3) after (6).

Mock some methods

Tested class


public class ExampleLogic2 {
    private String privateMethod() {
        return "abc";
    }
    public String publicMethod() {
        String str = privateMethod();
        return str.toUpperCase();
    }
}

Test class


import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class) //(1)
@PrepareForTest(ExampleLogic2.class) //(2)
public class ExampleLogicTest2 {

    @Test
    public void publicMethod() throws Exception {
        ExampleLogic2 logic = spy(new ExampleLogic2()); //(3)
        when(logic, "privateMethod").thenReturn("str"); //(4)
        assertThat(logic.publicMethod(), equalTo("STR"));
    }
}

(1) This is a magical trick required when using PowerMock. (2) Specify the class to be tested. (3) In order to mock some methods, new the test target class and call spy. (4) Set the return value of the method to be mocked (private in this example).

Recommended Posts

Mockito + PowerMock cheat sheet
Java cheat sheet
JMeter cheat sheet
Kotlin cheat sheet
[Docker cheat sheet]
Eclipse Collections cheat sheet
Rails Tutorial cheat sheet
Spring Boot2 cheat sheet
SCSS notation cheat sheet
Oreshiki docker-compose cheat sheet
Docker command cheat sheet
Java Stream API cheat sheet
[Eclipse] Shortcut key cheat sheet
C # cheat sheet for Java engineers
Competitive programming private cheat sheet (Java)
javac, jar, java command cheat sheet
Proper use of Mockito and PowerMock
Technology for reading source code (cheat sheet)
[Java] Data type / string class cheat sheet
Basic cheat sheet by language (Ruby, PHP)