I'm trying to get my head around fixtures in Spek. The Calculator example in the docs is easy to follow, but I'm not sure how to go about structuring setup/teardown when some of the fixtures are stateful. For example, if I was testing a list:
describe("a list") {
val list = arrayListOf<Int>() // Only instantiated once
on("adding an item") {
list.add(123)
it("has a size of one") {
list.size.should.equal(1)
}
}
on("adding 2 items") {
list.add(1)
list.add(2)
it("has a size of 2") {
list.size.should.equal(2) // Fails, 3 != 2
}
}
}
From what I understand, in Spek the describe
block is only evaluated once, so there is only ever one instance of List. The docs helpfully suggest using test fixtures, but then unhelpfully fail to give an example!
I assume the following doesn't work because Kotlin doesn't understand that Spek will definitely call beforeEachTest
before on
describe("a list") {
var list : MutableList<Int>
beforeEachTest {
list = arrayListOf()
}
on("adding an item") {
list.add(123) // Compile error, list must be initialised
I can get around that by making the variable nullable, but then I have to use nullsafe operators everywhere, which sucks because I know it's never null:
describe("a list") {
var list : MutableList<Int>? = null
beforeEachTest {
list = arrayListOf()
}
on("adding an item") {
list?.add(123) // Bleh
This also works, but means that every bit of setup code now needs to be duplicated in two places
describe("a list") {
var list = arrayListOf<Int>()
beforeEachTest {
list = arrayListOf() // Bleh
}
on("adding an item") {
list.add(123)
Excuse me if any of this is obvious, but I'm coming from JUnit world where absolutely everything (bar statics) is torn down and rebuilt before every test, so this all seems rather alien!
Aucun commentaire:
Enregistrer un commentaire