[Mockito] Argument Matchers – any(), eq()

Mockito는 mock 오브젝트를 생성하거나, behavior 테스트 케이스를 작성할 수 있는 stub을 생성 할 수 있도록 해 준다. 일반적으로는 behavior 테스트 mock을 생성할때 when() 과 thenReturn() 을 사용 한다.


Mockito Argument Matchers – any()

이따금, behavior mock을 작성할때 함수의 argument type으로 아무 type이나 주고 싶을 때가 있는데 이럴때 argument matchers를 사용하면 될것이다. Mockito argument methods 는 org.mockito.ArgumentMatchers클래스에 static method로 정의 되어 있다.
아래 method들이 있을 때,

class Foo {
 boolean bool(String str, int i, Object obj) {
  return false;
 }

 int in(boolean b, List<String> strs) {
  return 0;
 }
 
 int bar(byte[] bytes, String[] s, int i) {
  return 0;
 }
}
arguments를 generic 하게 쓰기 위해 아래처럼 mockito argument matchers를 사용할 수 있다. 주의할 점은 matchers를 사용하게 되면 모든 argument에 다 쓰던지 아니면 안쓰던지 해야지 argument 몇개만 사용하게 되면 에러가 발생한다. All or Nothing~~.

Foo mockFoo = mock(Foo.class);
when(mockFoo.bool(anyString(), anyInt(), any(Object.class))).thenReturn(true);
아래 예를 보면 bool() method가 어떤 string, integer, object arguments에도 “true”를 리턴할 수 있도록 되어 있다.

assertTrue(mockFoo.bool("A", 1, "A"));
assertTrue(mockFoo.bool("B", 10, new Object()));


Mockito Argument Matcher – eq()

arguments matcher를 사용중 특정한 값을 사용하고 싶을때는 eq() method를 사용해야 한다.

when(mockFoo.bool(eq("false"), anyInt(), any(Object.class))).thenReturn(false);
assertFalse(mockFoo.bool("false", 10, new Object()));
아래 list에 대한 예가 있고 set과 map등도 마찬가지로 사용할 수 있다.

when(mockFoo.in(anyBoolean(), anyList())).thenReturn(10);
만약에 arrays를 사용하고 싶으면 아래처럼 any() method를 사용할 수 있다.

any(byte[].class)
any(Object[].class)


Mockito AdditionalMatchers

Mockito org.mockito.AdditionalMatchers 클래스에 잘 사용되진 않지만 비교 연산을 위한 다양한 matcher들도 있다. 또한 array의 동등성 비교도 할 수 있다.

when(mockFoo.bar(any(byte[].class), aryEq(new String[] { "A", "B" }), gt(10))).thenReturn(11);
만약에 첫번째 argument로 byte array를, 두번째 argument로 { “A”, “B” }를, 세번째 argument로 10보다 큰 정수를 가지는 bar() method를 호출하면 11의 값을return 한다는 것을 검증한다면 아래의 예처럼 될 수 있다.

assertEquals(11, mockFoo.bar("abc".getBytes(), new String[] { "A", "B" }, 20));
assertEquals(11, mockFoo.bar("xyz".getBytes(), new String[] { "A", "B" }, 99));


Mockito Verify Argument Matchers

Mockito argument matchers는 when(),  verify() method 와만 같이 사용할 수 있다. 아래는 verify method를 사용하는 예이다.

verify(mockFoo, atLeast(0)).bool(anyString(), anyInt(), any(Object.class));
verify(mockFoo, atLeast(0)).bool(eq("false"), anyInt(), any(Object.class));


Summary

Mockito argument matcher methods는 behavior 테스트 케이스 작성시 generic한 변수 설정을 할 수 있도록 많은 도움을 준다. 시간이 되면 다른 method들도 정리는 해보자.

댓글

이 블로그의 인기 게시물

Orange for Oracle에서 한글 깨짐 해결책

[Protocol] WIEGAND 통신

[UI] GNB·LNB·SNB·FNB 용어 설명