JUnit and Kotlin Test
JUnit and Kotlin Test are libraries that you can use to unit test your code so that you can always have a safety net.
Add the JUnit library
you can add these lines to your build.gradle file:
dependencies{
testimplementation 'org.junit.jupiter:jupiter:junit-jupiter-api:5.3.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.31'
test{useJUnitPlatform}
}
So let me show you how to write the JUnit with Kotlin. Let's create a class :
class Totaller(var total : Int =0)
{
fun add (num: Int) : Int{
total+ = num
return total
}
}
Create a JUnit test class like below :
class Totaller(var total : Int =0)
{
fun add (num: Int) : Int{
total+ = num
return total
}
}
TotallerTest:
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class TotallerTest
{
@Test
fun shouldBeAbleToAdd3And4()
{
val totaller = Totaller()
assertEquals(3 , totaller.add(3))
assertEquals(3 , totaller.add(4))
assertEquals(3 , totaller.total)
}
}
Points to take a note on:
1) We are using code from the JUnit packages so we need to import them.
2)The TotallerTest class is used to test Totaller
3)@Test is an annotation that marks the following function as a test.
4)Tests are made up of actions and assertions.
5)Actions are a piece of code that does stuff while assertions are pieces of code that check stuff.
Now We will use the KotlinTest :
The KotlinTest library has been designed to use the full bread of the Kotlin language to write tests in a more expressive way.
KotlinTest is pretty vast and it allows you to write tests in many different styles but here is one way of writing a KotlinTest version of the JUnit code.
import io.kotlintest.shouldBe
imnport io.kotlintest.specs.StringSpec
class AnotherTotallerTest :StringSpec({
"Should be able to add 3 and 4 - and it must not go wrong"{
val totaller = TotallerTest()
totaller.add(3) shouldBe 3
totaller.add(4) shouldBe 7
totaller.total shouldBe 7
}
Points to take a note on:
This is String Specification or StringSpec style.
Now we will use rows to test against sets of data
import io.kotlintest.data.forall
import io.kotlintest.shoudBe
import io.kotlintest.specs.StringSpec
import io.kotlintest.tables.rows
class AnotherTotallerTest :StringSpec({
"Should be able to add 3 and 4 - and it must not go wrong"{
val totaller = TotallerTest()
totaller.add(3) shouldBe 3
totaller.add(4) shouldBe 7
totaller.total shouldBe 7
}
"should be able to add lots of different numbers"{
forall(
row(1,2,3),
row(19,47,66),
row(11,21,32)
){ x,y,expectedTotal - >
val totaller = TotallerTest(x)
totaller.add(y) shouldBe expectedTotal
}
}
})
Points to take a note on:
- Run test in parallel
- Create tests with generated properties
- Enable/disable tests dynamically. you may, for example, want some test to run only on Linux and others to run on Mac.
- Put tests in groups.
No comments:
Post a Comment