programing

@SpringBootConfiguration을 찾을 수 없습니다. 테스트에서 @ContextConfiguration 또는 @SpringBootTest(classes=...)를 사용해야 합니다.

codeshow 2023. 2. 26. 10:18
반응형

@SpringBootConfiguration을 찾을 수 없습니다. 테스트에서 @ContextConfiguration 또는 @SpringBootTest(classes=...)를 사용해야 합니다.

사용하고 있다Spring Data JPA그리고.Spring 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

내 개체의 저장소는 다음과 같습니다.

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

또한 저장소 구성을 제공했습니다.

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

저의 메인 어플리케이션은 다음과 같습니다.

@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);
        };
    }
}

응용 프로그램 테스트는 다음과 같습니다.

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

    @Test
    public void contextLoads() {
    }

}

저장소 테스트는 다음과 같습니다.

@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;
    }
}

하지만 테스트를 실행하려고 하면 오류가 발생합니다.

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)

뭐가 문제죠?도메인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;
}

src/test/java패키지 및src/main/java패키지가 일치해야 합니다.저도 같은 문제가 있었는데

  • 나의src/main/java패키지는 com.comp.downs로 시작했지만
  • src/test/java패키지는 com.sample.disples로 시작되었습니다.

이 스프링 부트애플리케이션으로 인해 어플리케이션 설정을 픽업할 수 없었습니다.@SpringBootApplication따라서 테스트 케이스는 같은 패키지에 속해야 합니다.@SpringBootApplicationsrc/main/java라고 쓰여져 있습니다.

스프링 부트가 시작되면 프로젝트의 맨 위에서 맨 아래로 클래스 경로를 스캔하여 구성 파일을 찾습니다.설정이 다른 파일 아래에 있기 때문에 문제가 발생합니다.설정을 모노리스 패키지로 이동하면 모든 것이 정상입니다.

@SpringBootTest에는 라는 이름의 파라미터가 있습니다.classes설정용으로 클래스 배열을 받아들입니다.컨피규레이션파일의 클래스를 추가합니다.다음은 예를 제시하겠습니다.

@SpringBootTest(classes={com.lapots.game.monolith.web.GrandJourneyMonolithApplication.class})

테스트src/test/java파일도 같은 디렉토리 구조를 따라야 합니다.src/main/java.

여기에 이미지 설명 입력

내 경우는 수업의 일부[이동/붙여넣기] 때문이었다.일부 사용자에게는package구가 [올바르게 업데이트되지 않음| 존재하지 않음]으로 변경 내용이 선택되지 않고 IDE가 선택되었습니다.

어쨌든, 프로젝트의 패키징을 재검토해 주세요.

프로젝트에 테스트 가능한 코드가 없고 스프링 부트 기본 테스트 클래스에 기본 테스트 블록이 있는 경우

@SpringBootTest

class DemoApplicationTests {
    @Test
    void contextLoads() {
    }
}

테스트 주석 및 contextLoads() 메서드를 삭제합니다.

@SpringBootTest
class DemoApplicationTests {
}

파일 삭제module-info.java이건 나한테 효과가 있었어.

이 문제를 해결할 수 있었던 것은, 다음의 항목을 포함시키고 나서입니다.@SpringBootTest는 컨텍스트컨피규레이션클래스와 응용 프로그램클래스를 모두 클래스 합니다.

언급URL : https://stackoverflow.com/questions/47487609/unable-to-find-a-springbootconfiguration-you-need-to-use-contextconfiguration

반응형