【问题标题】:Spring Boot DataJpaTest fail with java.lang.IllegalStateException:Caused by: Given type must be an interfaceSpring Boot DataJpaTest 因 java.lang.IllegalStateException 失败:原因:给定类型必须是接口
【发布时间】:2020-09-30 10:20:08
【问题描述】:

确切地说取决于我有什么错误。

如果我使用 Intellij Maven 安装,我会得到这个异常(这很奇怪,因为我有这个依赖关系,如果我没记错的话,它应该默认在 spring-starter-test 中):

Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.turbo.TurboFilter

但是如果我直接在有问题的测试类中开始测试,我会得到这个异常:

o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@217ed35e] to prepare test instance [mypackage.DataBaseTest@279fedbd]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
...
Caused by: java.lang.IllegalArgumentException: Given type must be an interface!
    at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]

对于第一个异常(Maven->Install)我不明白,我有那个类的那个 jar。

-External Libraries
    |
    |
    |--- Maven: ch.qos.logback:logback-classic:1.2.3
         |---logback-classic-1.2.3.jar
             |
             |---turbo
                 |
                 |---TurboFilter

对于第二个例外,我无法理解 @DataJpaTest 是否创建了所有内容。我尝试使用@SpringBootTest(认为它可能是我使用自动装配存储库的@Service)。

我正在使用 Spring Boot 2,jUnit5 和 Spring-boot-starter-test,没有 jUnit4。

我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
...
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
    <dependency>
        <groupId>weblogic</groupId>
        <artifactId>wljmsclient</artifactId>
        <version>12.1.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- Tomcat embedded container-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.oracle.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>12.2.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.6.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.200</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
        <scope>test</scope>
    </dependency>

应用配置:

@Configuration
@EnableJms
@EnableJpaRepositories
@PropertySource({"classpath:some.properties"})
public class ApplicationConfig {
...

private Properties getJNDiProperties() {
    final Properties jndiProps = new Properties();
    jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    return jndiProps;
}
@Bean
public JndiTemplate jndiTemplate() {
    final JndiTemplate jndiTemplate = new JndiTemplate();
    jndiTemplate.setEnvironment(getJNDiProperties());
    return jndiTemplate;
}

application.properties 文件:

spring.datasource.jndi-name=jdbc/myDataSource
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.generate-ddl=false

我没有任何测试应用程序配置。

application.properties 是空的,我什么都没有,因为我认为 @DataJpaTest 会为我创建一切。其他测试都很好,但只有带有 @DataJpaTest 的测试类因提到的异常而失败。

package myPackage;

import myPackage.repository.MyRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
public class DataBaseTest {


    @Autowired
    private DataSource dataSource;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private MyRepository myRepository;

    @Test
    public void injectedComponentsAreNotNull(){
        assertThat(dataSource).isNotNull();
        assertThat(jdbcTemplate).isNotNull();
        assertThat(entityManager).isNotNull();
        assertThat(myRepository).isNotNull();
    }
}

但是如果我删除 @DataJpaTest 并添加 @SpringBootConfiguration 和 @EnableAutoConfiguration 而不是所有自动装配的对象都是空的。

我不明白为什么 Spring Boot 不自动装配这些对象。

更新

所以,我只使用@DataJpaTest 添加@Import(MyRepository.class) 但我有同样的例外。

Maven->安装

Caused by: java.lang.ClassNotFoundException: ch.qos.logback.classic.turbo.TurboFilter

还有课!!!

IntelliJ->运行测试类

o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@217ed35e] to prepare test instance [mypackage.DataBaseTest@279fedbd]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
...
Caused by: java.lang.IllegalArgumentException: Given type must be an interface!
    at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-5.1.4.RELEASE.jar:5.1.4.RELEASE]

更新 2

我之所以有 ClassNotFoundException ch.qos.logback.classic.turbo.Filter 是因为我遇到了 slf4j 和 maven surefire 的问题,所以我排除了 logback:

            <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven-surefire-plugin.version}</version>
            <configuration>
                <classpathDependencyExcludes>
                    <classpathDependencyExcludes>ch.qos.logback:logback-classic</classpathDependencyExcludes>
                </classpathDependencyExcludes>
            </configuration>
        </plugin>

我删除了这个配置,现在我遇到了与直接从 IntelliJ 运行时相同的异常。

Caused by: java.lang.IllegalArgumentException: Given type must be an interface!

更新 3

最后,我取得了进展。我需要的是@EnableAutoConfiguration。 我以为@DataJpaTest 会为我做事,但显然,它有问题。

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Schema "MYSCHEMA" not found; SQL statement:

我有这样的实体:

@Getter
@Setter
@ToString
@Builder(toBuilder=true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = "logId")
@Entity
@Table(name = "MY_TABLE", schema = "MYSCHEMA", catalog = "")
public class MyEntity {

我需要一个用于测试的架构。

我试过这个,但没有帮助:

@TestPropertySource(properties = "spring.jpa.properties.hibernate.default_schema=PETRA")

【问题讨论】:

    标签: spring-data-jpa junit5 spring-test


    【解决方案1】:

    您的@DataJpaTest 不需要@EnableAutoConfiguration,因为注释启用了测试此应用程序部分所需的每个部分:

    // ... and some more
    @BootstrapWith(DataJpaTestContextBootstrapper.class)
    @ExtendWith(SpringExtension.class)
    @OverrideAutoConfiguration(enabled = false)
    @TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
    @Transactional
    @AutoConfigureCache
    @AutoConfigureDataJpa
    @AutoConfigureTestDatabase
    @AutoConfigureTestEntityManager
    @ImportAutoConfiguration
    public @interface DataJpaTest {
    
    }
    

    值得一提的是,@DataJpaTest Spring 默认会使用嵌入式内存数据库:

     * By default, tests annotated with {@code @DataJpaTest} are transactional and roll back
     * at the end of each test. They also use an embedded in-memory database (replacing any
     * explicit or usually auto-configured DataSource). The
     * {@link AutoConfigureTestDatabase @AutoConfigureTestDatabase} annotation can be used to
     * override these settings.
    

    这就是您看到 H2 数据库输出而不是 Oracle 的原因。默认情况下,Spring 应该使用spring.jpa.hibernate.ddl-auto=create-drop 来确保您的表存在。

    当您使用@Table(name = "MY_TABLE", schema = "MYSCHEMA", catalog = "") 硬编码 JPA 实体内的架构时,您必须确保嵌入式 H2 也使用此架构。

    首先尝试从@Table注解中删除schema,看看是否有效。然后,您可以在 application.properties 中全局配置您的架构,并使用 @TestPropertySource(properties = "spring.jpa.properties.hibernate.default_schema=PETRA") 进行测试。

    以下StackOverflow question 也可能有帮助。

    【讨论】:

    • thnx,我知道,但这很奇怪......当我添加它时(在我尝试使用 @SpringBootTest 之后)它起作用了,但又失败了,最后,我弄明白了。这是因为我在 test 中命名了一个与 main 相同的存储库类。所以 Spring Boot 很困惑,但反应总是不同,这很奇怪。它应该工作与否。所以,我删除了这个同名的类(没有 Component 注释),删除了那个注释,我只有 @DataJpaTest 并且它工作得很好。
    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2015-05-10
    • 2017-11-22
    相关资源
    最近更新 更多