기능 개발을 하다보면 상태 값에 따라 특정 기능을 실행할지 말지 분기를 탈 필요가 있다.
class SomeService(
    private val someFeature: SomeFeature,
) {
    fun executeIfFlagIsOn(flag: Boolean) {
        if (flag) {
            this.someFeature.execute()
        }
    }
}
class SomeFeature {
    fun execute() {}
}위와 같이 SomeService#executeIfFlagIsOn 메서드는 flag 파라미터를 통해 SomeFeature기능을 실행할지 말지를 결정하는 코드가 있을 때,
MockK를 사용하여 SomeFeature의 기능이 실행되거나 안되었음을 테스트하기 위해서 wasNot(called: Called) infix function을 사용할 수 있다.
import io.kotest.core.spec.style.DescribeSpec
import io.mockk.called
import io.mockk.clearMocks
import io.mockk.mockk
import io.mockk.verify
class SomeServiceTest : DescribeSpec({
    val someFeatureMock = mockk<SomeFeature>(relaxed = true)
    val sut = SomeService(someFeature = someFeatureMock)
    beforeTest {
        clearMocks(someFeatureMock)
    }
    context("executeIfFlagIsOn method는") {
        context("flag가 true인 경우") {
            it("기능을 실행한다") {
                // when
                sut.executeIfFlagIsOn(flag = true)
                // then
                verify {
                    someFeatureMock.execute() // execute 메서드가 실행됨
                }
            }
        }
        context("falg가 false인 경우") {
            it("기능을 실행하지 않는다") {
                // when
                sut.executeIfFlagIsOn(flag = false)
                // then
                verify {
                    someFeatureMock wasNot called // mock 객체가 사용되지 않음
                }
            }
        }
    }
})

'Java & Kotlin > Kotlin' 카테고리의 다른 글
| Kotlin + Spring MVC 사용 시 요청 List 필드에 null이 들어가는 경우 (0) | 2025.03.03 | 
|---|---|
| reified를 통해 generic type 정보 가져오기 (0) | 2023.01.16 | 
| JPA entity의 VO로 Kotlin value class 사용하기 (3) | 2022.06.01 | 
| [MockK] 메서드 호출 순서 검증하기 (0) | 2022.04.15 | 
| [MockK] 인자 값 그대로 리턴하기 (0) | 2022.04.14 | 
 
										
									 
										
									 
										
									
댓글