Yusuke Hosonuma
August 24, 2019
1.2k

# KotlinTest で始める Property-based Testing/kotlintest-property-based-testing

August 24, 2019

## Transcript

KotlinTest Ͱ࢝ΊΔ
Property-based Testing
Yusuke Hosonuma
@DeNA
Kotlin Fest 2019

Yusuke Hosonuma
@DeNA

SoftWare Engineer in Test
ςετࣗಈԽʢiOS / Android / Goʣ
CI/CDɺςετٕज़ͷݚڀ

ࣥච \$PNNJOHTPPOʜ

Agenda
• KotlinTest ͬͯʁ

• Property-based Testing ͬͯʁ

• ͲΜͳͱ͖ʹ࢖͑Δʁ

• ·ͱΊ ͳΜͱͳ͘ཧղ͕ΰʔϧ

6. KotlinTest ͬͯʁ
·ͣ

KotlinTest

KotlinTest
ଟ͘ͷػೳΛαϙʔτ͢Δ

ςεςΟϯάϑϨʔϜϫʔΫ

ςεςΟϯάελΠϧ
String Spec Behavior Spec
Feature Spec
#%%

ϚονϟʔAPI
ʴ

ςʔϒϧۦಈςετ
σʔλΛࣄલʹྻڍ

ςʔϒϧۦಈςετ
σʔλΛࣄલʹྻڍ
ΘΓͱશ෦੝Γͳ

ςεςΟϯάϑϨʔϜϫʔΫ
ͱ͍͏ҹ৅

13. Property-based Testing
ͬͯʁ
͡Ό͋

Property-based Testing
• ςετσʔλΛϥϯμϜʹੜ੒ͤ͞

• ؔ਺͕ຬͨ͢ੑ࣭ʢPropertyʣΛݕূ͢Δ

Property-based Testing
• ςετσʔλΛϥϯμϜʹੜ੒ͤ͞

• ͦͷؔ਺͕ຬͨ͢ੑ࣭ʢPropertyʣΛݕূ͢Δ
ͳΔ΄ͲɺΘ͔ΒΜɻ
ྫΛݟͯΈΔ

16. ଍͠ࢉʢʴʣͷ
ςετͰൺֱ

17. Example-based Testing
ීஈ΍ͬͯΔ

1 + 1 = 2 / 2 + 3 = 5
forall(
row(1, 1, 2),
row(2, 3, 5)
) { a, b, expected ->
(a + b) shouldBe expected
}
}
})

forall(
row(1, 1, 2),
row(2, 3, 5)
) { a, b, expected ->
(a + b) shouldBe expected
}
}
})
ೖྗ஋ͱظ଴஋Λ༻ҙͯ͠
1 + 1 = 2 / 2 + 3 = 5

forall(
row(1, 1, 2),
row(2, 3, 5)
) { a, b, expected ->
(a + b) shouldBe expected
}
}
})
݁Ռͱظ଴஋͕Ұக͢Δ͔ʁ
1 + 1 = 2 / 2 + 3 = 5

21. Property-based Testing
Ͱ͸ʁ

ੑ࣭Λߟ͑Δ
a + b = b + a
ަ׵๏ଇΛຬͨ͢

ੑ࣭Λߟ͑Δ
a + b = b + a
ʁ
ʁ
ͲΜͳ஋Ͱ΋੒Γཱͭ

KotlinTestͰݕূ
"commutative" {
assertAll { a: Int, b: Int ->
(a + b) shouldBe (b + a)
}
}
})

KotlinTestͰݕূ
“commutative" {
assertAll { a: Int, b: Int ->
(a + b) shouldBe (b + a)
}
}
})
͢΂ͯͷ

KotlinTestͰݕূ
“commutative" {
assertAll { a: Int, b: Int ->
(a + b) shouldBe (b + a)
}
}
})
औΓ͏Δ஋BͱCʹ͍ͭͯ

KotlinTestͰݕূ
"commutative" {
assertAll { a: Int, b: Int ->
(a + b) shouldBe (b + a)
}
}
}) BCCBͰ͋Δ͜ͱ

KotlinTestͰݕূ
"commutative" {
assertAll { a: Int, b: Int ->
(a + b) shouldBe (b + a)
}
}
}) BCCBͰ͋Δ͜ͱ
ϥϯμϜͳೖྗ஋ʹରͯ͠

ຬͨ͞ΕΔ΂͖ੑ࣭Λݕূ
ৗʹ

debug print ͯ͠ΈΔͱ
ཚ਺Ͱ ճࢼߦ͞ΕͯΔ

debug print ͯ͠ΈΔͱ
ཚ਺Ͱ ճࢼߦ͞ΕͯΔ
ύε͠ͳ͍σʔλ͕ͳ͍͔

େྔͷཚ਺Ͱ͋ͿΓग़͢
ͱߟ͑Δͱ෼͔Γ΍͍͢

31. ͲΜͳ࣌ʹ࢖͑Δʁ
Ͱ͸

࢖͍Ͳ͜Ζ
1. ཚ਺Λར༻ͨ͠ΞϧΰϦζϜ

2. ରশੑͷ͋ΔΞϧΰϦζϜ

3. ߴ଎ vs ௿଎

33. ཚ਺Λར༻ͨ͠ΞϧΰϦζϜ

໎࿏ੜ੒
• ͲΜͳ໎࿏Ͱ΋ղ͚ͳ͍ͱ੒ཱ͠ͳ͍

• ʮඞͣղ͚Δʯͱ͍͏ੑ࣭Λݕূ͢Δ

໎࿏ੜ੒
• ͲΜͳ໎࿏Ͱ΋ղ͚ͳ͍ͱ੒ཱ͠ͳ͍

• ٯʹݴ͑͹ղ͚ͳ͍ͱόά

• ʮඞͣղ͚Δʯͱ͍͏ੑ࣭Λݕূ͢Δ
ྫ͑͹
Monkey Runner ΋

ϥϯμϜͳΠϕϯτΛൃߦ͠ଓ͚

ʮམͪͳ͍ʯੑ࣭Λݕূ͢Δ
"OESPJEͷ

36. ରশੑͷ͋ΔΞϧΰϦζϜ

Τϯίʔυ / σίʔυ
• ͲΜͳ஋ΛΤϯίʔυ → σίʔυ ͯ͠΋

• ඞͣʮݩͷ஋ʹ໭Δʯͱ͍͏ੑ࣭Λݕূ

38. ߴ଎ vs ௿଎

ߴ଎ vs ௿଎
• ߴ଎ͳίʔυ͸଎͍ʢ͚Ͳෳࡶʣ

• ௿଎ͳίʔυ͸໌നʢ͚Ͳ஗͍ʣ

• ͲͪΒ΋ʮಉ݁͡ՌʹͳΔʯͱ͍͏ੑ࣭Λར༻

• લऀͷݕূʹޙऀΛར༻͢Δ

40. ·ͱΊ

·ͱΊ
• KotlinTest ͸ ςεςΟϯάϑϨʔϜϫʔΫ
• Property-based Testing ΋αϙʔτ

• ϥϯμϜͳೖྗΛݩʹੑ࣭Λݕূ

• Example-based Λஔ͖׵͑Δ΋ͷͰ͸ͳ͍

·ͱΊ
• KotlinTest ͸ DSL Λ׆༻ͨ͠ςετϥΠϒϥϦ

• Property-based Testing ΋αϙʔτ

• ϥϯμϜͳೖྗΛݩʹੑ࣭Λݕূ

• Example-based Λஔ͖׵͑Δ΋ͷͰ͸ͳ͍
ͱ͖ͬͭͮΒ͍ߟ͑ํ͕ͩ

͓֮͑ͯ͘ͱڧྗͳΧʔυ
࠷ॳ͸

43. એ఻