Testing exceptions

The set method of the ToDoStorage class can throw ToDoAlreadyExistException:

operator fun set(name: String, todo: ToDo): Boolean {
if (todos.contains(name)) {
throw ToDoAlreadyExistException()
}
todos[name] = todo

return true
}

It is also important to make sure that this exception will be thrown when it is needed. For this, we can write one more test that checks whether ToDoAlreadyException is thrown when a user tries to store a todo with a key that already exists.

We need to add a dependency to the kotlintest library (https://github.com/kotlintest/kotlintest) to be able to use the shouldThrow function. After integrating this library, your dependencies section in the build.gradle file will look as follows:

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.0'
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.6.1"
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'
testCompile 'io.kotlintest:kotlintest-runner-junit5:3.1.7'
}

Let's add a test that checks whether ToDoAlreadyException is thrown:

on("set a todo with a key that already stored") {
it ("should throw ToDoAlreadyExistException") {
shouldThrow<ToDoAlreadyExistException> {
val todo = ToDo("name", "content")
storage.set("name", todo)
}
}
}

After running this, you will see the following window:

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

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