EasyMockのVoidメソッドで、expectLastCall()を利用する。

「時々、私たちはvoidメソッドをモックしたくなることがあります。EasyMockのexpect()メソッドは、voidメソッドをモックすることができません。しかし、expectLastCall()メソッドとandAnswer()メソッドを組み合わせて、voidメソッドをモックすることができます。」

EasyMockのvoidメソッド

void UtilityClass {
void performAction(String arg1, int arg2) {
// perform some action
}
}

In JMockit, we can mock this void method as follows:

void testUtilityClass() {
new Expectations() {{
UtilityClass mock = new UtilityClass();
mock.performAction(anyString, anyInt);
expectLastCall().andAnswer(
new ExpectationsUtil.Delegate() {
void delegate(Invocation inv) {
Object[] args = inv.getCurrentArguments();
// perform some action on args
return null;
}
});
}};
}

package com.scdev.utils;

public class StringUtils {

	public void print(String s) {
		System.out.println(s);
	}
}

EasyMockを使用して、voidメソッドprint()をモックするためのコードがこちらにあります。

package com.scdev.easymock;

import static org.easymock.EasyMock.*;

import org.junit.jupiter.api.Test;

import com.scdev.utils.StringUtils;

public class EasyMockVoidMethodExample {

  @Test
  public void test() {
    StringUtils mock = mock(StringUtils.class);
    
    mock.print(anyString());
    expectLastCall().andAnswer(() -> {
      System.out.println("Mock Argument = "
          +getCurrentArguments()[0]);
      return null;
    }).times(2);
    replay(mock);
    
    mock.print("Java");
    mock.print("Python");
    verify(mock);
  }
}
EasyMock void method

`expectLastCall().andVoid()` の日本語での表現は次の通りです:
`expectLastCall().andReturn()`

モックオブジェクト上のvoidメソッドを単にモック化し、特定のロジックを実行したくない場合は、voidメソッドを呼び出した後に単純にexpectLastCall().andVoid()を使用することができます。

弊社のGitHubリポジトリから、完全なプロジェクトとさらに多くのEasyMockの例をチェックアウトすることができます。

コメントを残す 0

Your email address will not be published. Required fields are marked *