How to use dependency injection in Spek tests

I do simple microservices using Kotlin, Spring and Spek. I want to check my repository, but I am wondering how I can insert a repo into a spek test file. Each example or tutorial is based on creating a new link:

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 summarize, I don't want to do this:

 val calculator = SampleCalculator() 

I want to achieve this

 @Autowired val calculator: SampleCalculator 

but I cannot do this because I cannot use auto services in a local variable. Any solutions? I am new to kotlin and spek.

+7
source share
2 answers

Try with lateinit :

 @Autowired lateinit var calculator: SampleCalculator 
0
source

Take a look at the spek-spring-extension project on GitHub, there is a way to implement bean components from the Spring context:

Spring extension for Spek

This is a confirmation of the concept of writing spring integration tests in Spek

Limitations

Currently, only the introduction of beans is supported.

 @ContextConfiguration(classes = arrayOf(MyConfiguration::class)) object MySpec: Spek({ val context = createContext(MySpec::class) val foo = context.inject<Foo>() // val foo: Foo by context.inject() it("blah blah blah") { foo.doSomething() } }) 

the questions

The Spring TestContext environment makes assumptions about how the tests are arranged, which is incompatible with Spek, which means that we cannot use TestContextManager (we can, but it will be very hacky).

0
source

Source: https://habr.com/ru/post/1014724/


All Articles