未使用KotlinTest 3.1.8初始化Spring Autowire

时间:2018-09-13 20:03:13

标签: spring kotlin kotlintest

我知道这应该可行,因为其他人报告说它可以工作。但是,在一个简单的“演示”项目(Spring Initializer)中,我无法在测试中初始化autowired属性。

当我在“ JpaTestApplicationTests”中执行测试时,我无法过去收到“ lateinit属性回购尚未初始化 kotlin.UninitializedPropertyAccessException”。

有人可以帮助我了解我在做什么错吗?

以下是我的应用程序文件,要自动装配的bean和进行测试:

应用程序:

package com.example.jpaTest

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class JpaTestApplication

fun main(args: Array<String>) {
    SpringApplication.run(JpaTestApplication::class.java, *args)
}

Bean:

package com.example.jpaTest

import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository

@Repository
interface FakeRepository : CrudRepository<Fake, String>

测试:

package com.example.jpaTest

import io.kotlintest.*
import io.kotlintest.specs.*
import io.kotlintest.spring.SpringListener
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration

@ContextConfiguration(classes = [JpaTestApplication::class])
class JpaTestApplicationTests : StringSpec() {
    override fun listeners() = listOf(SpringListener)

    @Autowired
    lateinit var repo: FakeRepository

    init {
        "can get by id"{
            val it = Fake("Blah","testName1")
            val saved = repo.save(it)

            repo.findOne(saved.uuid) shouldBe saved
        }
    }
}

相关Gradle条目:

  buildscript {
    ext {
      kotlinVersion = '1.2.61'
      springBootVersion = '1.5.16.RELEASE'
    }
    repositories {
      mavenCentral()
    }
    dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
      classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
      classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
      classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlinVersion"
    }
  }

  apply plugin: 'kotlin'
  apply plugin: 'kotlin-spring'
  apply plugin: "kotlin-jpa"
  apply plugin: 'org.springframework.boot'

  test {
      useJUnitPlatform()
  }

  dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('com.fasterxml.jackson.module:jackson-module-kotlin')
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
    compile("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")

      testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile 'io.kotlintest:kotlintest-runner-junit5:3.1.8'
      testCompile 'io.kotlintest:kotlintest-extensions-spring:3.1.8'
  }

0 个答案:

没有答案