0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JUnit】生成したインスタンスの一部メソッドだけモック化する

Last updated at Posted at 2024-07-30

junitでのテスト時に、生成したインスタンスのメソッドを一部だけモック化したい場合があり、やり方をちょくちょく忘れるので記録

junit version

pom.xml
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
	<scope>test</scope>
</dependency>

以下のようなサンプルクラスを使います

public class Person {
	private final String name;
	private final int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String greet() {
		StringBuilder sb = new StringBuilder();
		sb.append(sayName()).append("\n").append(sayAge()).append("\n");
		return sb.toString();
	}

	String sayName() {
		return "Hello, my name is " + name + ".";
	}

	String sayAge() {
		return "I am " + age + " years old.";
	}
}

サンプルコード

@Test
public void test() {
	Person person1 = new Person("Alice", 20);
	System.out.println(person1.greet());
 
    // spy
	Person person2 = Mockito.spy(person1);
	Mockito.when(person2.sayName()).thenReturn("Hello, my name is Bob.");
	System.out.println(person2.greet());
}

出力結果

Hello, my name is Alice.
I am 20 years old.

Hello, my name is Bob.
I am 20 years old.

上記のように生成したインスタンスに対してspyを用意し、特定のメソッドをwhen + thenReturnでモック化します

  • 対象メソッドがprivateの場合失敗する
  • 今回のようにthenReturn()を使用する場合はメソッド内部の処理が実行されるので、実行せず指定した返却値だけ返したい場合はdoReturn()を使用

参考 : https://qiita.com/vossibop/items/2956d4c5734419b6bac2

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?