Mockito는 유연한 객체의 조작(stubbing)이나 함수 호출을 검증하기 위해 인수 일치자(argument matcher)를 제공합니다.
각 Mockito.verify(), Mockito.when(), Stubber.when(), BDDMockito.given() 함수는 인수 일치자 유무와 상관없이 오버로드를 할 수 있습니다. 그러나 기본 일치 동작(즉, 인수 일치자가 없는 경우)은 equals()를 사용합니다.
만약 오직 org.mockito.ArgumentMatchers.eq() 일치자만 사용된다면, 그 호출은 일치자 없이 호출한 것과 동일합니다. 즉, eq() 함수는 불필요하고 생략할 수 있습니다.
이렇게 적용한 코드는 더 짧아지고 읽기 쉬워집니다.
규칙을 어긴 코드
@Test
public void myTest() {
given(foo.bar(eq(v1), eq(v2), eq(v3))).willReturn(null); // 규칙을 어긴 코드
when(foo.baz(eq(v4), eq(v5))).thenReturn("foo"); // 규칙을 어긴 코드
doThrow(new RuntimeException()).when(foo).quux(eq(42)); // 규칙을 어긴 코드
verify(foo).bar(eq(v1), eq(v2), eq(v3)); // 규칙을 어긴 코드
}
규칙을 준수한 코드
@Test
public void myTest() {
given(foo.bar(v1, v2, v3)).willReturn(null);
when(foo.baz(v4, v5)).thenReturn("foo");
doThrow(new RuntimeException()).when(foo).quux(42);
verify(foo).bar(v1, v2, v3);
}
참고
- Mockito documentation - argument matchers
- {rule:java:S6073} - Mockito argument matchers should be used on all parameters
If you like SONARKUBE, don’t forget to give me a star. ![]()