Spring Boot公共库项目中的单元测试

时间:2019-01-29 03:08:08

标签: java spring-boot gradle junit kotlin

我的问题是如何配置gradle和spring boot以在不应用org.springframework.boot插件的情况下运行公共库项目的单元测试?

我有一个用gradle构建的Spring Boot公共库项目。 问题是:

  • 我不想将org.springframework.boot插件应用到我的项目中,因为它应用于Spring Boot应用程序,但应用于库项目。

  • 我需要在测试中连接(@Autowired)一些bean。

  • 我尝试如下配置我的build.gradle文件

buildscript {
    ext {
        springBootVersion = '2.0.4.RELEASE'
        junitPlatformVersion = '1.0.0-M2'
    }
    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: 'eclipse'
//apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

jar {
    baseName = 'my-common-lib'
    version = '0.0.1-SNAPSHOT'
}

sourceCompatibility = 1.8
compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

repositories {
    mavenCentral()
}

test {
    useJUnitPlatform()
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.boot:spring-boot-dependencies:$springBootVersion"
    }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    compile("org.jetbrains.kotlin:kotlin-reflect")

    testCompile('org.springframework.boot:spring-boot-starter-test') {
        exclude module: 'junit'
    }
    testCompile group: 'org.assertj', name: 'assertj-core', version: assertjCoreVersion

    testImplementation('org.junit.jupiter:junit-jupiter-api')
    testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine')
}
  • 我的测试如下:
@ExtendWith(SpringExtension::class)
@SpringBootTest
class MyCommonLibraryTest(@Autowired val myBean: MyBean) {
  @Test
  ...
}
  • 最后,运行测试时我被抛出BeanCreationException
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherBean' defined in class path resource [com/pipedbits/spiralg/templateengine/infrastructure/configuration/TemplateConfiguration.class]: Unexpected exception during bean creation; nested exception is java.lang.IllegalStateException: Resource not found in classpath: kotlin/coroutines/coroutines.kotlin_builtins

0 个答案:

没有答案