java 无法找到 @SpringBootConfiguration,您需要在测试中使用 @ContextConfiguration 或 @SpringBootTest(classes=...)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47487609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:38:33  来源:igfitidea点击:

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

javaspring-bootspring-data-jpaspring-test

提问by lapots

I am using Spring Data JPAand Spring Boot. The layout of the application is this

我正在使用Spring Data JPASpring Boot。应用程序的布局是这样的

main
    +-- java
        +-- com/lapots/game/monolith
            +-- repository/relational
                +--RelationalPlayerRepository.java
            +-- web
                +--GrandJourneyMonolithApplication.java
                +-- config
                    +-- RelationalDBConfiguration.java
test
    +-- java
        +-- com/lapots/game/monolith
            +-- repository/relational
                +-- RelationalPlayerRepositoryTests.java
            +-- web
                +-- GrandJourneyMonolithApplicationTests.java

The repository for my object looks like this

我的对象的存储库看起来像这样

public interface RelationalPlayerRepository extends JpaRepository<Player, Long> {
}

Additionally for the repositories I provided a configuration

另外对于存储库,我提供了一个配置

@Configuration
@EnableJpaRepositories(basePackages = "com.lapots.game.monolith.repository.relational")
@EntityScan("com.lapots.game.monolith.domain")
public class RelationalDBConfiguration {
}

My main application looks like this

我的主要应用程序看起来像这样

@SpringBootApplication
@ComponentScan("com.lapots.game.monolith")
public class GrandJourneyMonolithApplication {

    @Autowired
    private RelationalPlayerRepository relationalPlayerRepository;

    public static void main(String[] args) {
        SpringApplication.run(GrandJourneyMonolithApplication.class, args);
    }

    @Bean
    public CommandLineRunner initPlayers() {
        return (args) -> {
            Player p = new Player();
            p.setLevel(10);
            p.setName("Master1909");
            p.setClazz("warrior");

            relationalPlayerRepository.save(p);
        };
    }
}

Test for application looks like this

应用程序测试看起来像这样

@RunWith(SpringRunner.class)
@SpringBootTest
public class GrandJourneyMonolithApplicationTests {

    @Test
    public void contextLoads() {
    }

}

The test for repository looks like this

存储库的测试如下所示

@RunWith(SpringRunner.class)
@DataJpaTest
public class RelationalPlayerRepositoryTests {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private RelationalPlayerRepository repository;

    @Test
    public void testBasic() {
        Player expected = createPlayer("Master12", "warrior", 10);
        this.entityManager.persist(expected);
        List<Player> players = repository.findAll();
        assertThat(repository.findAll()).isNotEmpty();
        assertEquals(expected, players.get(0));
    }

    private Player createPlayer(String name, String clazz, int level) {
        Player p = new Player();
        p.setId(1L);
        p.setName(name);
        p.setClazz(clazz);
        p.setLevel(level);
        return p;
    }
}

But when I try to run the tests I get the error

但是当我尝试运行测试时出现错误

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.041 sec <<< FAILURE! - in com.lapots.game.monolith.repository.relational.RelationalPlayerRepositoryTests
initializationError(com.lapots.game.monolith.repository.relational.RelationalPlayerRepositoryTests)  Time elapsed: 0.006 sec  <<< ERROR!
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:70)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:202)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:137)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:409)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:323)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:277)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:112)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:82)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

What is the problem? Domain Playerloooks like this

问题是什么?域Player看起来像这样

@Data
@Entity
@Table(schema = "app", name = "players")
public class Player {
    @Id
    @GeneratedValue
    private Long id;

    @Transient
    Set<Player> comrades;

    @Column(unique = true)
    private String name;

    private int level;

    @Column(name = "class")
    private String clazz;
}

采纳答案by Yuriy Tsarkov

When the SpringBoot starts it scans classpath from the top to the bottom of the project to find the config file. Your config is under another files and that is a reason of the problem. Move you config upper to the monolithpackage and everything gonna be fine

当 SpringBoot 启动时,它会从项目的顶部到底部扫描类路径以找到配置文件。您的配置在另一个文件下,这就是问题的原因。将你的配置移到整体包上,一切都会好起来的

回答by Saurabh Parmar

src/test/javapackages and src/main/javapackages should match. I had same issue where my src/main/javapackages were starting with com.comp.examplebut src/test/javapackages were starting with com.sample.example. Because of this spring boot application was not able to pickup the configuration of the application which it picks up from @SpringBootApplicationclass. So test case should fall under the packages where @SpringBootApplicationin src/main/javais written.

src/test/java包和src/main/java包应该匹配。我有同样的问题,我的src/main/java包以com.comp.example开头,但src/test/java包以com.sample.example开头。由于这个 spring boot 应用程序无法获取它从@SpringBootApplication类中获取的应用程序的配置。所以测试用例应该属于写@SpringBootApplicationin的包src/main/java

回答by VC2019

I am using Spring Boot with a simple REST controller. Not using any JPA and was getting same error as specified in the title here for my controller test. Also I am using a custom configuration for my Spring boot app. The 2nd answer above (answered Oct 19 '18 at 7:20 Saurabh Parmar) helped. The root cause for me too was the package name. The package for my test under the src/test/java was not matching the one under the src/main/java. Once I fixed that it worked.

我正在使用带有简单 REST 控制器的 Spring Boot。没有使用任何 JPA,并且在我的控制器测试中遇到与标题中指定的相同的错误。此外,我正在为我的 Spring Boot 应用程序使用自定义配置。上面的第二个答案(Saurabh Parmar 于 18 年 10 月 19 日 7:20 回答)有所帮助。我的根本原因也是包名称。我在 src/test/java 下的测试包与 src/main/java 下的包不匹配。一旦我确定它起作用了。