0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Junit5 + Mockitoでstaticメソッドのモック化

Last updated at Posted at 2023-08-10

junit5とMockitoを使用してstaticメソッドのモック化をしようとした際に、junit4やPowerMockitoを使用した情報やMockitoのバージョンによるエラーで詰まったので記録します。

pom.xml

pom.xml
    ...
    <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>11</java.version>
		<mockito.version>4.4.0</mockito.version>
	</properties>
    ...
	<dependencies>
		<!-- mockito -->
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<version>${mockito.version}</version>
			<scope>test</scope>
		</dependency>
        <!-- mockStaticで使用 -->
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-inline</artifactId>
			<version>${mockito.version}</version>
		</dependency>

		<!-- junit5を含む -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

今回はmockito-coremockito-inlineのバージョンを4.4.0に揃えていますが、4.5.*4.6.*にあげるとこちらにあるようなエラーが出てしまってうまくいきませんでした。
https://github.com/mockito/mockito/issues/2629

モック対象メソッド

public class Sample {
    public static boolean doSomething() {
        return false;
    }
}

Test

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import ...Sample;

public class SampleTest {
    @Test
    public void test() {
        try (MockedStatic<Sample> mock = Mockito.mockStatic(Sample.class)) {
            Mockito.when(mock.doSomething()).thenReturn(true);
            Assertions.assertEquals(true, mock.doSomething());
        }
    }
}

MockedStaticクラスはcloseする必要があるためtry-with-resource文にしています。
junit4のアノテーションやPowerMockitoが混在しているとエラーが起きたため、統一した書き方をする必要がありそうです。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?