2

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

当我在“JpaTestApplicationTests”中执行测试时,我无法通过接收“lateinit property repo has not been initialized 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)
}

豆:

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'
  }
4

0 回答 0