Kotlin 筆記
好孩子的十萬個為什麼
為什麼這次Kotlin的學習我會以單元測試來開頭,因為我通常會用簡單的單元測試,當作新技術學習的開始,前提是該技術並非與UI有密切的耦合。
事前準備
IDE:IntelliJ IDEA
Android Studio
Test Frameworks: JUnit 5
Mocking: MockK
Assertions: AssertJ
開新專案

設定
在build.gradle的dependencies中加上參考
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testCompile "junit:junit:4.12"
}
打草稿
寫程式不用猴急胡亂打一通,先想清楚業務邏輯整體流程,把複雜的地方切割、整理、歸類,打好草稿就可以逐一突破了。一般我們會以抽象類別或介面當作起手式,這邊我的目的在於簡單驗證單元測試的可行性,所以就隨便做個物件吧。
class Calculator {
fun divide(a: Int, b: Int): Double {
if (b == 0)
throw IllegalArgumentException("division by zero!")
return a.toDouble() / b
}
fun add(a: Int, b: Int): Int {
return a + b
}
}
測試案例
範例寫了兩個測試。
需注意的是這裡僅import org.junit.*
import org.junit.*
class CalculatorTest {
private lateinit var calculator: Calculator
@Before
fun setup() {
this.calculator = Calculator()
}
@After
fun cleanup() {
}
@Test(expected = IllegalArgumentException::class)
fun testDivide() {
val result = this.calculator.divide(2, 0)
Assert.assertEquals(2.0, result, 0.0001)
}
@Test
fun testAdd() {
val result = this.calculator.add(1, 5)
Assert.assertEquals(6, result)
}
}