파라미터로 넘어오는 값 확인하기

MyList myList = mock(MyList.class); ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class); doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); myList.add(0, "captured"); assertEquals("captured", valueCapture.getValue()); https://www.baeldung.com/mockito-void-methods

2024-09-15 · 1 min · 15 words

특정 메소드가 호출된 횟수 검증

Mockito.verify(utilClass, Mockito.times(1)).method(); https://stackoverflow.com/questions/57775074/mockito-veify-is-giving-wrong-invocation-count

2024-09-15 · 1 min · 3 words

스태틱 메소드 목킹하기

이를 사용하기 위해서는 mockito 의존을 새로 추가해야된다. mockito-inline 를 추가해야된다. mockito-core를 대체할 수 있다. testImplementation 'org.mockito:mockito-inline:4.2.0' 정적 메소드를 목킹하기위해서는 먼저 MockedStatic 객체를 만들어야된다. 이 객체는 AutoClosable 이기때문에 try-with-resources로 감싸는게 좋다. try-with-resource 블럭 내부에서는 목킹이 되고, 밖으로 벗어나면 적용되지 않는다. @Test void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { assertThat(StaticUtils.name()).isEqualTo("Baeldung"); try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) { utilities.when(StaticUtils::name).thenReturn("Eugen"); assertThat(StaticUtils.name()).isEqualTo("Eugen"); } assertThat(StaticUtils.name()).isEqualTo("Baeldung"); } @Test void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) { utilities....

2024-09-15 · 1 min · 91 words

반환 값이 void인 메소드 아무것도 하지 않게 mocking

doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); https://www.baeldung.com/mockito-void-methods

2024-09-15 · 1 min · 3 words

모든 메서드 호출 로깅하기

목표 mocking 한 객체들의 메서드 호출들을 모두 로깅하도록 한다. MockSettings 일반적으로 mockito를 이용해서 목킹할 때 mock(MyClass.class) 형태로 목칭을 하지만, 두번째 인자로 목킹할 때 추가적인 설정을 할 수 있다. MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); MyList listMock = mock(MyList.class, customSettings); MockSettings에는 invocationListeners를 등록할 수 있고, 이는 목킹한 객체에 메서드 호출이 발생할 때 동작하는 리스너다. List mockWithListener = mock(MyList.class, withSettings().invocationListeners(new YourInvocationListener())); Mockito-Kotlin 도 이를 지원하고 있고, 이를 통해서 호출된 메서드가 무엇인지 로깅할 수 있다....

2024-09-15 · 1 min · 86 words

verify

목표 mockito의 verify() 메서드를 통해 검증할 수 있는 내용들을 알아본다. 호출된 횟수 검증 List<String> mockedList = mock(MyList.class); mockedList.size(); verify(mockedList, times(1)).size(); 호출되지 않음을 검증 List<String> mockedList = mock(MyList.class); mockedList.size(); verify(mockedList, never()).clear(); 호출되는 인자 매칭 커스터마이징 인자 매칭 기준이 복잡하다면 ArgumentMatchers.argThat() 을 통해서 매칭 기준을 커스터마이징할 수 있다. 인자로 ArgumentMatcher라는 함수형 인터페이스를 받고 있어서 람다로 구체적인 조건을 명시할 수 있다. 참고 자료 https://www.baeldung.com/mockito-verify https://www.baeldung.com/mockito-argument-matchers

2024-09-15 · 1 min · 62 words

thenAnswer vs thenReturn

목표 thenAnswer와 thenReturn의 차이를 알아본다. 차이점 thenReturn은 정적인 반환 값을 설정할 때 사용한다. thenAnswer은 호출에 대한 추가적은 작업이 필요하거나, 동적인 반환 값이 필요할 때 사용한다. thenAnswer thenAnswer는 Answer 타입의 인자를 갖는다. Answer는 함수형 인터페이스이다. 아래 사진처럼 Answer의 메서드의 인자인 InvocationOnMock은 호출한 메소드의 인자를 반환하거나, 해당 메소드를 반환, mocking한 대상 객체를 반환도 할 수 있어서 유연하게 사용할 수 있다. 참고 자료 https://stacktraceguru.com/unittest/thenreturn-vs-thenanswer https://www.baeldung.com/mockito-additionalanswers https://javadoc.io/static/org.mockito/mockito-core/3.1.0/org/mockito/invocation/InvocationOnMock.html

2024-09-15 · 1 min · 63 words

Mutable 한 객체 테스트 시 주의점

배경 객체의 상태를 변화시키면서 같은 메서드를 호출하는 경우 Mockito로 검증하는데 계속 실패했다. class MutableService(val mutableMessageQueue: MutableMessageQueue) { fun run() { val mutable = Mutable() val nextNames = listOf("a", "b", "c", "d") for (nextName in nextNames) { mutable.name = nextName mutableMessageQueue.publish(mutable) } } } class MutableMessageQueue { fun publish(mutable: Mutable?) { if (mutable != null) { println(mutable.name) } } } data class Mutable(var name: String = "") class MutableTest { lateinit var mutableMessageQueue: MutableMessageQueue lateinit var mutableService: MutableService @Test fun test() { // given mutableMessageQueue = mock() mutableService = MutableService(mutableMessageQueue) // when mutableService....

2024-09-15 · 1 min · 195 words

Mockito 테스트 작성하기

@ExtendWith(MockitoExtension.class) public class BoTest { @Mock private Dao dao; @InjectMocks private Bo bo; @Test public void test() { given(dao.findById(anyLong())) .willReturn(new Object()); } }

2024-09-15 · 1 min · 23 words

Mocking한 객체의 메소드 인자 상태 확인

Mocking한 상태인 orderTableDao 에서 orderTableDao.save(entity) 를 호출했을 때, entity의 필드값을 검증할 필요가 있었다. argThat() 메서드를 사용하면 검증이 가능하다. verify(orderTableDao, times(3)).save( argThat(orderTable -> !orderTable.isEmpty() && Objects.nonNull(orderTable.getTableGroupId()) ) ); 참고 자료 https://stackoverflow.com/questions/31993439/can-mockito-verify-an-argument-has-certain-properties-fields https://www.baeldung.com/mockito-argument-matchers

2024-09-15 · 1 min · 31 words

given vs when

목표 mockito의 given과 when 함수의 차이점을 이해한다. Mockito vs. BDDMockito 기본적으로 given과 when함수의 동작은 같다. 둘 다 특정 객체를 목킹하여 함수의 동작을 정의할 때 사용할 수 있다. given은 when을 BDD 스타일로 작성할 수 있도록 만든 함수다. given은 BDDMockito에 정의되어있고, when은 Mockito에 정의되어 있다. BDDMockito는 Mockito 를 상속한 클래스다. BDD(Behavior Driven Development) TDD의 한 종류로 시나리오를 기반으로 테스트 케이스를 작성하여, 개발자가 아닌 사람이 봐도 이해할 수 있을 정도의 테스트 코드를 작성하는 것이다....

2024-09-15 · 1 min · 117 words