18
18

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 5 years have passed since last update.

mockitoでstaticなメソッドをMock化する

Posted at

PowerMockを使用する

mockitoでstaticメソッドはMock化できないのでPowerMockを使用する。

ソース

テスト対象クラス

MoriUtilA.java
public class MoriUtilA {
	public static String getMoriString(String inStr){
		return "あなたは" + MoriUtilB.isMoriorHayashi(inStr) + "です";
	}
}

モック化するクラス

MoriUtilB.java
public class MoriUtilB {
	public static String isMoriorHayashi(String inStr){
		// 入力値が「もり」なら「森」を、それ以外なら「林」を返す
		return "";// 未作成
	}
}

インポート文

import static org.powermock.api.mockito.PowerMockito.when;
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;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;

テストクラス

MoriUtilATest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest({MoriUtilB.class})
public class MoriUtilATest {
	@Before
	public void setUp() throws Exception {
		// MoriUtilBをモック
		PowerMockito.mockStatic(MoriUtilB.class);
	}
	@Test
	public void mockTestMori() {
		// モックの返却値を設定
		when(MoriUtilB.isMoriorHayashi("もり")).thenReturn("森");
		// 実施
		String actual = MoriUtilA.getMoriString("もり");
		assertEquals("あなたは森です", actual);
	}
	@Test
	public void mockTestHayashi() {
		// モックの返却値を設定
		when(MoriUtilB.isMoriorHayashi(anyString())).thenReturn("林");
		// 実施
		String actual = MoriUtilA.getMoriString("林");
		assertEquals("あなたは林です", actual);
	}
}

pom.xml

pom.xml
<dependency>
	<groupId>org.mockito</groupId>
	<artifactId>mockito-all</artifactId>
	<version>1.9.5</version>
	<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
	<dependency>
		<groupId>org.mockito</groupId>
		<artifactId>mockito-core</artifactId>
		<scope>test</scope>
	</dependency>
<dependency>
	<groupId>org.powermock</groupId>
	<artifactId>powermock-api-mockito</artifactId>
	<version>1.5.4</version>
	<scope>test</scope>
</dependency>
<dependency>
	<groupId>org.powermock</groupId>
	<artifactId>powermock-module-junit4</artifactId>
	<version>1.5.4</version>
	<scope>test</scope>
</dependency>
18
18
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
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?