I am implementing simple microservice using Kotlin, Spring and Spek. I want to test my repository but I wonder how can I inject repo into spek test case. Every example or tutorial base on creating new reference like this:
object SampleTest : Spek({
describe("a calculator") {
val calculator = SampleCalculator()
it("should return the result of adding the first number to the second number") {
val sum = calculator.sum(2, 4)
assertEquals(6, sum)
}
it("should return the result of subtracting the second number from the first number") {
val subtract = calculator.subtract(4, 2)
assertEquals(2, subtract)
}
}
})
To summup I dont want to do sth like this:
val calculator = SampleCalculator()
I want to achieve this
@Autowired
val calculator: SampleCalculator
but I cant to that becasue I cant autowire service into local variable.. Any solutions ? I am new in kotlin and spek.
Dependency Injection is a way of injecting the dependencies into your class. Your class declares it's dependencies (e.g. via a constructor parameter) and whoever is using your class can provide those dependencies. This way we don't hard-code dependencies into our classes and our codebase is a lot more flexible.
Dependency Injection is NOT Just for Testing.
What Is Spek? Spek is a Kotlin-based Specification Testing framework for the JVM. It's designed to work as a JUnit 5 Test Engine. This means that we can easily plug it into any project that already uses JUnit 5 to run alongside any other tests that we might have.
Try it with lateinit:
@Autowired
lateinit var calculator: SampleCalculator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With