Created
June 7, 2017 13:11
-
-
Save robfletcher/3d1dd03572efd008ccbc44c9ca125d3b to your computer and use it in GitHub Desktop.
Example of trying to use `SubjectSpek` and `itBehavesLike` if the subject requires a collaborator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jetbrains.spek.api.dsl.describe | |
import org.jetbrains.spek.api.dsl.given | |
import org.jetbrains.spek.api.dsl.it | |
import org.jetbrains.spek.api.dsl.on | |
import org.jetbrains.spek.subject.SubjectSpek | |
import org.jetbrains.spek.subject.itBehavesLike | |
import org.junit.Assert.assertFalse | |
import org.junit.Assert.assertTrue | |
open class Thing(protected val fn: () -> Unit) { | |
fun doIfEven(n: Int) { | |
if (n % 2 == 0) fn() | |
} | |
} | |
object ThingSpec : SubjectSpek<Thing>({ | |
// mock collaborator is only visible inside this block | |
val mockFn = object : () -> Unit { | |
var invoked = false | |
override fun invoke() { | |
invoked = true | |
} | |
fun reset() { | |
invoked = false | |
} | |
} | |
subject { | |
// constructor of subject depends on collaborator | |
Thing(mockFn) | |
} | |
describe("doIfEven") { | |
given("an even parameter") { | |
afterGroup(mockFn::reset) | |
on("calling doIfEven") { | |
subject.doIfEven(2) | |
} | |
it("invokes the function") { | |
assertTrue("mock was not invoked", mockFn.invoked) | |
} | |
} | |
given("an odd parameter") { | |
afterGroup(mockFn::reset) | |
on("calling doIfEven") { | |
subject.doIfEven(1) | |
} | |
it("does not invoke the function") { | |
assertFalse("mock should not have been invoked", mockFn.invoked) | |
} | |
} | |
} | |
}) | |
class ExtendedThing(fn: () -> Unit) : Thing(fn) | |
object ExtendedThingSpec : SubjectSpek<ExtendedThing>({ | |
subject { | |
// no way to access collaborator required to run tests in ThingSpec | |
ExtendedThing(mockFn) | |
} | |
itBehavesLike(ThingSpec) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment