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】doReturn, thenReturnでの違い

Posted at

junitで単体テストを書いているときに、when + thenReturndoReturn + whenの違いがよくわからなかったのですが、spyを使う場合に少し違いがあったので記録します

junit version

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

以下のようなサンプルクラスでテストしてみます

public class Sample {
	@Getter
	private boolean active = false;

	public boolean init(boolean active) {
		this.active = active;
		return active;
	}
}

mockの場合

@Test
public void test() {
    // thenReturn
	Sample sample1 = Mockito.mock(Sample.class);
	Mockito.when(sample1.init(true)).thenReturn(false);
	assertFalse(sample1.init(true));
	assertTrue(sample1.isActive());

    // doReturn
	Sample sample2 = Mockito.mock(Sample.class);
	Mockito.doReturn(false).when(sample2).init(true);
	assertFalse(sample2.init(true));
	assertFalse(sample2.isActive());
}

-> 差分なし.メソッド内部の処理は実行されず指定した返却値のみ返される

spyの場合

@Test
public void test() {
    // thenReturn
	Sample sample1 = Mockito.spy(new Sample());
	Mockito.when(sample1.init(true)).thenReturn(false);
	assertFalse(sample1.init(true));
	assertTrue(sample1.isActive());

    // doReturn
	Sample sample2 = Mockito.spy(new Sample());
	Mockito.doReturn(false).when(sample2).init(true);
	assertFalse(sample2.init(true));
	assertFalse(sample2.isActive());
}

-> thenReturnの場合メソッド内部の処理は実行され、指定した返却値が返される

ちなみに、他にもthenReturnだとvoidメソッドはスタブ化できないなどあるみたいです

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?