Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dependency injection in Spek tests

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.

like image 500
user3528733 Avatar asked Feb 06 '17 09:02

user3528733


People also ask

How is dependency injection used in testing?

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.

Is dependency injection only for testing?

Dependency Injection is NOT Just for Testing.

What is Spek framework?

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.


1 Answers

Try it with lateinit:

@Autowired
lateinit var calculator: SampleCalculator
like image 68
loc Avatar answered Oct 11 '22 20:10

loc