Testing examples

In this section, we will practice writing tests with the Spek framework. We touched on the benefits of this framework and automated testing in the previous sections, and we are ready to test the functionality of the ToDoStorage class from Chapter 10, Exception Handling. Let's modify the build.gradle file to integrate the Spek framework and Unit engine, as follows:

 buildscript {
//.......
dependencies {
+ classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0'
}
}
//.........
+ apply plugin: 'org.junit.platform.gradle.plugin'

+ junitPlatform {
+ filters {
+ engines {
+ include 'spek'
+ }
+ }
+ }

repositories {
//.........
+ maven { url "http://dl.bintray.com/jetbrains/spek" }
}
dependencies {
//.........
+ testCompile 'org.jetbrains.spek:spek-api:1.1.5'
+ testRuntime 'org.jetbrains.spek:spek-junit-platform-engine:1.1.5'
+ testCompile 'org.junit.platform:junit-platform-runner:1.0.0'
}

In our project, all of the source code is located in the main folder and all test code is located in the test folder. Let's create the ToDoSpek class in the chapter11 package to test the ToDoStorage class. The following screenshot shows what our new project structure looks like:

Let's define the ToDoSpek class, as follows:

import chapter11.ToDoStorage
import org.jetbrains.spek.api.*
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith

@RunWith(JUnitPlatform::class)
object ToDoSpek: Spek({
//.....
})

To describe a specification, we should extend the Spek class. This class contains a constructor with a receiver and looks as follows:

abstract class Spek(val spec: Spec.() -> Unit) {
companion object {
fun wrap(spec: Spec.() -> Unit) = object: Spek(spec) {}
}
}

We already explored receivers in object-oriented patterns in Chapter 7, Coroutines - a Lightweight Thread? To be able to run our tests, we should mark the ToDoSpek class with the RunWith annotation and pass a class reference to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.56.12