๊ฐœ์š”

captured ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ฃผ์–ด์ง„ stub ์„ ์กฐ๊ฑด์ ˆ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

๋น„์ฆˆ๋‹ˆ์Šค ์ฝ”๋“œ

์•„๋ž˜์™€ ๊ฐ™์€ ๋กœ์ง์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค.

(coffeeGetService -> coffeeRepository)

// ์ปคํ”ผ ๊ฐ์ฒด
data class Coffee(
    val name: String,
    val price: Long
)

// ์ปคํ”ผ ์กฐํšŒ ์„œ๋น„์Šค
class CoffeeGetService(
    private val coffeeRepository: CoffeeRepository
) {

	// ๊ฐ€๊ฒฉ์— ๋”ฐ๋ฅธ ์ปคํ”ผ๋ชฉ๋ก์„ ์กฐํšŒํ•œ๋‹ค.
    fun getCoffeesByPrices(prices: List<Long>): List<Coffee> {
        return prices.map {
            coffeeRepository.findAllByPrice(it)
        }
            .flatten()
            .distinctBy { it }
    }
}

// ์ปคํ”ผ ๋ ˆํŒŒ์ง€ํ† ๋ฆฌ : ๋’ท๋‹จ์— ์Šคํ† ๋ฆฌ์ง€์™€ ์—ฐ๊ฒฐ๋˜์—ˆ๋‹ค๊ณ  ๊ฐ€์ •.
class CoffeeRepository {

    fun findAllByPrice(price: Long): List<Coffee> {
        return emptyList()
    }
}

 

ํ…Œ์ŠคํŠธ์ฝ”๋“œ

coffeeRepository.findAllByPrice(price: Long) ์„ ์ „๋‹ฌ๋ฐ›์„ ๋•Œ, capture(price) ๋กœ ๊ฑด๋„ค์ค€๋‹ค. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์šฐ๋ฆฌ๊ฐ€ mocking ๋œ ๊ฐ์ฒด์— ํ…Œ์ŠคํŠธ๋ฅผ ์œ„ํ•œ ์ธ์ž๋ฅผ ๊ฑด๋„ค์ค„ ๋•Œ, ์กฐ๊ฑด์— ๋งž๊ฒŒ ์‘๋‹ต๊ฐ’์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. (answers {} ๋ธ”๋Ÿญ์ด ํ•ด๋‹น ์˜ˆ์‹œ)

class CapturingTest {

    private val coffeeRepository: CoffeeRepository = mockk()
    private val coffeeGetService = CoffeeGetService(coffeeRepository)

    @Test
    @DisplayName("๊ธˆ์•ก์„ ๊ฑด๋„ค์ฃผ๊ณ , ๊ธˆ์•ก์— ๋งž๋Š” ์ปคํ”ผ์ข…๋ฅ˜๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.")
    fun capturingTest() {

        // given
        val price = slot<Long>()

        every { coffeeRepository.findAllByPrice(capture(price)) } answers {
            when (price.captured) {
                3000L -> {
                    listOf(Coffee("์•„๋ฉ”๋ฆฌ์นด๋…ธ", 3000L))
                }
                5000L -> {
                    listOf(Coffee("์นดํŽ˜๋ผ๋–ผ", 5000L))
                }
                8000L -> {
                    listOf(Coffee("์ฝœ๋“œ๋ธ”๋ฃจ", 8000L))
                }
                else -> {
                    emptyList()
                }
            }
        }

        // when
        val actual = coffeeGetService.getCoffeesByPrices(listOf(3000L, 5000L, 9000L))

        // then
        actual.asClue { coffee ->
            coffee.size shouldBe 2
            coffee.minByOrNull { it.price }!!.name shouldBe "์•„๋ฉ”๋ฆฌ์นด๋…ธ"
            coffee.maxByOrNull { it.price }!!.name shouldBe "์นดํŽ˜๋ผ๋–ผ"
        }
    }
}

 

ํ…Œ์ŠคํŠธ ์‹œ ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฐ์ฒด์™€ ๊ฑฐ๊ธฐ์— ์˜์กด๋œ mock ๊ฐ์ฒด์˜ ์‘๋‹ต์„ ์กฐ๊ฑด์— ๋”ฐ๋ผ ๋‹ค๋ฅด๊ฒŒ ์ฃผ๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๊ฒ ๋‹ค.

 

reference

https://mockk.io/

Posted by doubler
,