Spring Boot 2.1.1:java.lang.IllegalStateException:运行单元测试时无法检索@EnableAutoConfiguration基本包错误

时间:2019-01-08 08:20:47

标签: unit-testing spring-boot spring-data-jpa

执行单元测试时,将引发以下错误。请告知我是否错过了什么。我正在使用Spring Boot 2.1.1.RELEASE。谢谢!

  

java.lang.IllegalStateException:无法检索   @EnableAutoConfiguration基本软件包


application-test.yml

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/carkeeper_navigation"
app:startDestination="@id/mainFragment">

<fragment
    android:id="@+id/mainFragment"
    android:name="com.saicfinance.carkeeper.func.main.MainFragment"
    android:label="MainFragment"
    tools:layout="@layout/home_fragment">
</fragment>

<fragment
    android:id="@+id/mineFragment"
    android:name="com.saicfinance.carkeeper.func.mine.MineFragment"
    android:label="@string/mine_title"
    tools:layout="@layout/mine_fragment" >

    <action android:id="@+id/action_mine_fragment_to_setting_fragment"
        app:destination="@id/settingFragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_right"/>
</fragment>

<fragment
    android:id="@+id/settingFragment"
    android:name="com.freddy.func.setting.SettingFragment"
    android:label="setting_fragment"
    tools:layout="@layout/setting_fragment" />

AppRepository.java

spring:
  profiles: test
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
    username : xxx
    password : xxx
  jpa:
    hibernate:
      ddl-auto: update
  cache:
    type: simple

AppRepositoryTest.java

@Repository
public interface AppRepository extends CrudRepository<App, Integer> {

    App findFirstByAppId(String appId);

}   

包装结构

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppRepository.class})
@EnableConfigurationProperties
@DataJpaTest
@ActiveProfiles("test")
public class AppRepositoryTest {

    @Autowired
    AppRepository appRepository;

    @Before
    public void setUp() throws Exception {
        App app = new App();
        app.setAppId("testId");
        appRepository.save(app);
    }

    @Test
    public void testFindFirstByAppId() {
        assertNotNull(appRepository.findFirstByAppId("testId"));        
    }
}

3 个答案:

答案 0 :(得分:2)

我尝试了Zaccus的解决方案,但对我而言不起作用。我正在使用Spring Boot 2.3.2.RELEASE和JUnit5。对于我来说,我需要将模型和存储库移到一个单独的库中,因为它需要由我的Web应用程序和工具共享。

下面是我要做的工作:

没有main或SpringApplication的Spring Boot JPA测试

package com.example.repository;

import com.example.model.Place;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@ContextConfiguration(classes={PlaceRepositoryTest.class})
@EnableJpaRepositories(basePackages = {"com.example.*"})
@EntityScan("com.example.model")
public class PlaceRepositoryTest {
    @Autowired private DataSource dataSource;
    @Autowired private JdbcTemplate jdbcTemplate;
    @Autowired private EntityManager entityManager;
    @Autowired private PlaceRepository repo;

    @Test
    void testInjectedComponentsAreNotNull(){
        assertThat(dataSource).isNotNull();
        assertThat(jdbcTemplate).isNotNull();
        assertThat(entityManager).isNotNull();
        assertThat(repo).isNotNull();
    }

    @Test
    public void testInsert() throws Exception {
        String placeName = "San Francisco";
        Place p = new Place(null, placeName);

        repo.save(p);
        Optional<Place> op = repo.findByName(placeName);

        assertThat(op.isPresent()).isTrue();
    }
}

从Spring Boot 2.1开始,使用@DataJpaTest时,您不再需要指定

@ExtendWith(SpringExtension.class)
@EnableJpaRepositories(basePackages = {"com.example.*"})

对于我来说,因为PlaceRepository和PlaceRepositoryTest位于同一软件包中,所以不需要basePackages = {“ com.example。*”}。我只是在这里添加它,以防有人进行了测试,其中包括在不同软件包中找到的存储库。如果没有“ basePackages”,则默认情况下,@ EnableJpaRepositories会扫描带注释的配置类的包中的Spring Data存储库。

最初,我只有以下注释:

@DataJpaTest
@ContextConfiguration(classes={PlaceRepositoryTest.class})
@EnableJpaRepositories(basePackages = {"com.example.*"})

我发现的网站说我只需要@DataJpaTest和@EnableJpaRepositories,但是,仅通过上述操作,我得到以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
:
:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'placeRepository' defined in com.example.repository.PlaceRepository defined in @EnableJpaRepositories declared on PlaceRepositoryTest: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.model.Place

我花了一些时间才弄清楚。对于“非托管类型”,我认为班级Place出了点问题:

package com.example.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class Place {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    private String name;
}

根本原因是未将“地方”作为实体进行扫描。要解决此问题,我需要添加

@EntityScan("com.example.model")

我在stackoverflow的另一个解决方案中发现了“ @EntityScan”:Spring boot - Not an managed type

以下是我的设置:

src
 + main
    + java
       + com.example
          + model
             + Place
          + repository
             + PlaceRepository
 + test
    + java
       + com.example
          + repository
             + PlaceRepository
<?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>

    <groupId>org.example</groupId>
    <artifactId>jpa</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <properties>
        <spring.boot.starter.version>2.3.2.RELEASE</spring.boot.starter.version>
        <h2.version>1.4.200</h2.version>
        <lombok.version>1.18.12</lombok.version>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${spring.boot.starter.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${spring.boot.starter.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>${spring.boot.starter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
package com.example.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.model.Place;

import java.util.Optional;

@Repository
public interface PlaceRepository extends CrudRepository<Place, Long> {
    Optional<Place> findByName(String name);
}

答案 1 :(得分:1)

当我删除“ ActiveProfiles”和“ EnableConfigurationProperties”并最终在ContextConfiguration批注中指定Main类时,我设法使其正常工作。

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppMain.class})
@DataJpaTest
public class AppRepositoryTest {

    @Autowired
    AppRepository appRepository;

    @Before
    public void setUp() throws Exception {
        App app = new App();
        app.setAppId("testId");
        appRepository.save(app);
    }

    @Test
    public void testFindFirstByAppId() {
        assertNotNull(appRepository.findFirstByAppId("testId"));        
    }
}

答案 2 :(得分:0)

根据45.3 Testing Spring Boot Applications文档,启用Spring Boot功能(如@EnableAutoConfiguration)的推荐方法是使用@SpringBootTest而不是旧的@ContextConfiguration

  

Spring Boot提供了一个@SpringBootTest注释,当您需要Spring Boot功能时,它可以用作标准的spring-test @ContextConfiguration注释的替代方法。注释通过创建通过SpringApplication在测试中使用的ApplicationContext来起作用。除了@SpringBootTest以外,还提供了许多其他批注来测试应用程序的更具体的部分。

您可以尝试使用@ContextConfiguration编写测试,这是Spring Boot的部分设置,但是您会遇到类似的问题。 Spring Boot很大程度上基于惯例,例如组件扫描从包含@SpringBootApplication个带注释类的包开始。不建议您违反这些约定。