在Eclipse中,运行junit测试不会产生任何错误。
当我使用./gradlew test
时,出现此错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:106)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:117)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [config_targets]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1694)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:573)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1087)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:548)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 49 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [config_targets]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:402)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1753)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1690)
... 64 more
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [config_targets]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:121)
at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42)
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:89)
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:191)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
... 68 more
好吧,我不想创建config_targets
表,因为我的实体是这样的:
/**
* A Config.
*/
@Entity
@Table(name = "config")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Config implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "targets", nullable = false)
@ElementCollection
private List<String> targets;
在PostgreSQL中,目标由varchar[]
我不使用hibernate访问Config,而是使用jdbc来访问Config,但我使用它来建立Config与其他对象之间的关系。
我认为我的build.gradle
文件中有一些东西阻止测试通过,因为它可以在Eclipse中顺利运行
build.gradle:
import org.gradle.internal.os.OperatingSystem
buildscript {
repositories {
mavenLocal()
mavenCentral()
maven { url "http://repo.spring.io/plugins-release" }
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-
plugin:${spring_boot_version}"
classpath "io.spring.gradle:propdeps-plugin:0.0.10.RELEASE"
classpath "gradle.plugin.com.gorylenko.gradle-git-properties:gradle-git-properties:1.5.2"
//jhipster-needle-gradle-buildscript-dependency - JHipster will add additional gradle build script plugins here
}
}
plugins {
id "org.sonarqube" version "2.6.2"
id "net.ltgt.apt-eclipse" version "0.19"
id "net.ltgt.apt-idea" version "0.19"
id "net.ltgt.apt" version "0.19"
id "io.spring.dependency-management" version "1.0.6.RELEASE"
id 'org.liquibase.gradle' version '2.0.1'
//jhipster-needle-gradle-plugins - JHipster will add additional gradle plugins here
}
apply plugin: 'java'
sourceCompatibility=1.8
targetCompatibility=1.8
// Until JHipster supports JDK 9
assert System.properties['java.specification.version'] == '1.8'
apply plugin: 'maven'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
apply plugin: 'propdeps'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'idea'
idea {
module {
excludeDirs += files('node_modules')
}
}
dependencyManagement {
imports {
mavenBom 'io.github.jhipster:jhipster-dependencies:' + jhipster_dependencies_version
//jhipster-needle-gradle-dependency-management - JHipster will add additional dependencies management here
}
}
defaultTasks 'bootRun'
group = 'com.ins.mdm'
version = '0.0.1-SNAPSHOT'
description = ''
bootWar {
mainClassName = 'com.ins.mdm.MdmApp'
}
war {
enabled = true
extension = 'war.original'
}
springBoot {
mainClassName = 'com.ins.mdm.MdmApp'
}
if (OperatingSystem.current().isWindows()) {
// https://stackoverflow.com/questions/40037487/the-filename-or-extension-is-too-long-error-using-gradle
task classpathJar(type: Jar) {
dependsOn configurations.runtime
appendix = 'classpath'
doFirst {
manifest {
attributes 'Class-Path': configurations.runtime.files.collect {
it.toURI().toURL().toString().replaceFirst(/file:\/+/, '/').replaceAll(' ', '%20')
}.join(' ')
}
}
}
bootRun {
dependsOn classpathJar
doFirst {
classpath = files("$buildDir/classes/java/main", "$buildDir/resources/main", classpathJar.archivePath)
}
}
}
test {
exclude '**/CucumberTest*'
// uncomment if the tests reports are not generated
// see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
// ignoreFailures true
reports.html.enabled = false
}
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/tests")
reportOn test
}
apply from: 'gradle/docker.gradle'
apply from: 'gradle/sonar.gradle'
//jhipster-needle-gradle-apply-from - JHipster will add additional gradle scripts to be applied here
if (project.hasProperty('prod')) {
apply from: 'gradle/profile_prod.gradle'
} else {
apply from: 'gradle/profile_dev.gradle'
}
if (project.hasProperty('zipkin')) {
apply from: 'gradle/zipkin.gradle'
}
if (!project.hasProperty('runList')) {
project.ext.runList = 'main'
}
project.ext.diffChangelogFile = 'src/main/resources/config/liquibase/changelog/' + new Date().format('yyyyMMddHHmmss') + '_changelog.xml'
liquibase {
activities {
main {
driver 'org.h2.Driver'
url 'jdbc:h2:file:./target/h2db/db/mdm'
username 'mdm'
password ''
changeLogFile 'src/main/resources/config/liquibase/master.xml'
defaultSchemaName ''
logLevel 'debug'
classpath 'src/main/resources/'
}
diffLog {
driver 'org.h2.Driver'
url 'jdbc:h2:file:./target/h2db/db/mdm'
username 'mdm'
password ''
changeLogFile project.ext.diffChangelogFile
referenceUrl 'hibernate:spring:com.ins.mdm.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy'
defaultSchemaName ''
logLevel 'debug'
classpath "$buildDir/classes/java/main"
}
}
runList = project.ext.runList
}
configurations {
providedRuntime
compile.exclude module: "spring-boot-starter-tomcat"
}
repositories {
mavenLocal()
mavenCentral()
jcenter()
//jhipster-needle-gradle-repositories - JHipster will add additional repositories
}
dependencies {
// Use ", version: jhipster_dependencies_version, changing: true" if you want
// to use a SNAPSHOT release instead of a stable release
compile group: "io.github.jhipster", name: "jhipster-framework"
compile "org.springframework.boot:spring-boot-starter-cache"
compile "io.dropwizard.metrics:metrics-core"
compile 'io.micrometer:micrometer-registry-prometheus'
compile "net.logstash.logback:logstash-logback-encoder"
compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
compile "com.fasterxml.jackson.core:jackson-annotations"
compile "com.fasterxml.jackson.core:jackson-databind"
compile "com.fasterxml.jackson.module:jackson-module-afterburner"
compile "com.hazelcast:hazelcast"
compile "com.hazelcast:hazelcast-hibernate52"
compile "com.hazelcast:hazelcast-spring"
compile "javax.cache:cache-api"
compile "org.hibernate:hibernate-core"
compile "com.zaxxer:HikariCP"
compile "org.apache.commons:commons-lang3"
compile "commons-io:commons-io"
compile "javax.transaction:javax.transaction-api"
compile "org.hibernate:hibernate-entitymanager"
compile "org.hibernate:hibernate-envers"
compile "org.hibernate.validator:hibernate-validator"
compile "org.liquibase:liquibase-core"
compile "com.mattbertolini:liquibase-slf4j"
liquibaseRuntime "org.liquibase:liquibase-core"
liquibaseRuntime "org.liquibase.ext:liquibase-hibernate5:${liquibase_hibernate5_version}"
liquibaseRuntime sourceSets.main.compileClasspath
compile "org.springframework.boot:spring-boot-loader-tools"
compile "org.springframework.boot:spring-boot-starter-mail"
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-aop"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-security"
compile ("org.springframework.boot:spring-boot-starter-web") {
exclude module: 'spring-boot-starter-tomcat'
}
compile "org.springframework.boot:spring-boot-starter-undertow"
compile "org.springframework.boot:spring-boot-starter-thymeleaf"
compile "org.zalando:problem-spring-web:0.24.0-RC.0"
compile "org.springframework.cloud:spring-cloud-starter"
compile "org.springframework.cloud:spring-cloud-starter-netflix-ribbon"
compile "org.springframework.cloud:spring-cloud-starter-netflix-hystrix"
compile "org.springframework.retry:spring-retry"
compile "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client"
compile "org.springframework.cloud:spring-cloud-starter-config"
compile "org.springframework.cloud:spring-cloud-starter-openfeign"
compile "org.springframework.boot:spring-boot-starter-cloud-connectors"
compile "org.springframework.security:spring-security-config"
compile "org.springframework.security:spring-security-data"
compile "org.springframework.security:spring-security-web"
compile "io.jsonwebtoken:jjwt-api"
runtime "io.jsonwebtoken:jjwt-impl"
runtime "io.jsonwebtoken:jjwt-jackson"
compile ("io.springfox:springfox-swagger2") {
exclude module: 'mapstruct'
}
compile "io.springfox:springfox-bean-validators"
compile "org.postgresql:postgresql"
liquibaseRuntime "org.postgresql:postgresql"
compile "org.mapstruct:mapstruct-jdk8:${mapstruct_version}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstruct_version}"
annotationProcessor "org.hibernate:hibernate-jpamodelgen"
annotationProcessor ("org.springframework.boot:spring-boot-configuration-processor") {
exclude group: 'com.vaadin.external.google', module: 'android-json'
}
testCompile "com.jayway.jsonpath:json-path"
testCompile ("org.springframework.boot:spring-boot-starter-test") {
exclude group: 'com.vaadin.external.google', module: 'android-json'
}
testCompile "org.springframework.security:spring-security-test"
testCompile "org.springframework.boot:spring-boot-test"
testCompile "org.assertj:assertj-core"
testCompile "junit:junit"
testCompile "org.mockito:mockito-core"
testCompile "com.mattbertolini:liquibase-slf4j"
testCompile "org.hamcrest:hamcrest-library"
testCompile "com.h2database:h2"
liquibaseRuntime "com.h2database:h2"
//jhipster-needle-gradle-dependency - JHipster will add additional dependencies here
}
task cleanResources(type: Delete) {
delete 'build/resources'
}
wrapper {
gradleVersion = '4.10.2'
}
task stage(dependsOn: 'bootWar') {
}