IT

JpaTest를 수행 할 때 @SpringBootConfiguration을 찾을 수 없습니다

lottoking 2020. 6. 9. 07:49
반응형

JpaTest를 수행 할 때 @SpringBootConfiguration을 찾을 수 없습니다


나는 프레임 워크를 처음 접했고 (방금 수업을 통과했다) 스프링 부트를 사용한 것은 이번이 처음이다.

CrudRepositories가 실제로 작동하는지 확인하기 위해 간단한 Junit 테스트를 실행하려고합니다.

내가 계속 얻는 오류는 다음과 같습니다.

@SpringBootConfiguration을 찾을 수 없으면 테스트 java.lang.IllegalStateException과 함께 @ContextConfiguration 또는 @SpringBootTest (classes = ...)를 사용해야합니다.

Spring Boot는 자체적으로 구성하지 않습니까?

내 테스트 수업 :

@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class JpaTest {

@Autowired
private AccountRepository repository;

@After
public void clearDb(){
    repository.deleteAll();
}

 @Test
 public void createAccount(){
     long id = 12;
     Account u = new Account(id,"Tim Viz");
     repository.save(u);

     assertEquals(repository.findOne(id),u);

 }


 @Test
 public void findAccountByUsername(){
     long id = 12;
     String username = "Tim Viz";
     Account u = new Account(id,username);
     repository.save(u);

     assertEquals(repository.findByUsername(username),u);

 }

내 스프링 부트 애플리케이션 스타터 :

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"domain.repositories"})
@ComponentScan(basePackages = {"controllers","domain"})
@EnableWebMvc
@PropertySources(value    {@PropertySource("classpath:application.properties")})
    @EntityScan(basePackages={"domain"})
    public class Application extends SpringBootServletInitializer {
        public static void main(String[] args) {
            ApplicationContext ctx = SpringApplication.run(Application.class, args);         

        }
    }

내 저장소 :

public interface AccountRepository extends CrudRepository<Account,Long> {

    public Account findByUsername(String username);

    }
}

실제로 Spring Boot는 대부분 자체적으로 설정됩니다. 이미 게시 한 많은 코드, 특히에서 제거 할 수 있습니다 Application.

모든 클래스의 패키지 이름 또는 적어도 Application와에 대한 패키지 이름을 포함했으면합니다 JpaTest. 에 대한 건 @DataJpaTest과 몇 가지 다른 주석 그들이 찾는 것입니다 @SpringBootConfiguration현재 패키지에 주석하고, 그들이 거기에 그것을 찾을 수없는 경우 그들은 그것을 찾을 때까지, 그들은 패키지의 계층 구조를 통과.

예를 들어, 테스트 클래스의 정규화 된 이름 com.example.test.JpaTest과 응용 프로그램의 이름이 모두 com.example.Application인 경우 테스트 클래스는 @SpringBootApplication(및 내부에서 @SpringBootConfiguration) 를 찾을 수 있습니다 .

응용 프로그램 패키지의 계층 구조의 다른 지점에 거주하는 경우, 그러나, 같은 com.example.application.Application, 그것은 것입니다 하지 를 찾을 수 있습니다.

다음 Maven 프로젝트를 고려하십시오.

my-test-project
  +--pom.xml
  +--src
    +--main
      +--com
        +--example
          +--Application.java
    +--test
      +--com
        +--example
          +--test
            +--JpaTest.java

그리고 다음 내용은 Application.java:

package com.example;

@SpringBootApplication
public class Application {

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

Followed by the contents of JpaTest.java:

package com.example.test;

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

    @Test
    public void testDummy() {
    }
}

Everything should be working. If you create a new folder inside src/main/com/example called app, and then put your Application.java inside it (and update the package declaration inside the file), running the test will give you the following error:

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


Configuration is attached to the application class, so the following will set up everything correctly:

@SpringBootTest(classes = Application.class)

Example from the JHipster project here.


It is worth to check if you have refactored package name of your main class annotated with @SpringBootApplication. In that case the testcase should be in an appropriate package otherwise it will be looking for it in the older package . this was the case for me.


In addition to what Thomas Kåsene said, you can also add

@SpringBootTest(classes=com.package.path.class)

to the test annotation to specify where it should look for the other class if you didn't want to refactor your file hierarchy. This is what the error message hints at by saying:

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

In my case the packages were different between the Application and Test classes

package com.example.abc;
...
@SpringBootApplication
public class ProducerApplication {

and

package com.example.abc_etc;
...
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerApplicationTest {

After making them agree the tests ran correctly.


The test slice provided in Spring Boot 1.4 brought feature oriented test capabilities.

For example,

@JsonTest provides a simple Jackson environment to test the json serialization and deserialization.

@WebMvcTest provides a mock web environment, it can specify the controller class for test and inject the MockMvc in the test.

@WebMvcTest(PostController.class)
public class PostControllerMvcTest{

    @Inject MockMvc mockMvc;

}

@DataJpaTest will prepare an embedded database and provides basic JPA environment for the test.

@RestClientTest provides REST client environment for the test, esp the RestTemplateBuilder etc.

These annotations are not composed with SpringBootTest, they are combined with a series of AutoconfigureXXX and a @TypeExcludesFilter annotations.

Have a look at @DataJpaTest.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@OverrideAutoConfiguration(enabled = false)
@TypeExcludeFilters(DataJpaTypeExcludeFilter.class)
@Transactional
@AutoConfigureCache
@AutoConfigureDataJpa
@AutoConfigureTestDatabase
@AutoConfigureTestEntityManager
@ImportAutoConfiguration
public @interface DataJpaTest {}

You can add your @AutoconfigureXXX annotation to override the default config.

@AutoConfigureTestDatabase(replace=NONE)
@DataJpaTest
public class TestClass{
}

Let's have a look at your problem,

  1. Do not mix @DataJpaTest and @SpringBootTest, as said above @DataJpaTest will build the configuration in its own way(eg. by default, it will try to prepare an embedded H2 instead) from the application configuration inheritance. @DataJpaTest is designated for test slice.
  2. If you want to customize the configuration of @DataJpaTest, please read this official blog entry from Spring.io for this topic,(a little tedious).
  3. Split the configurations in Application into smaller configurations by features, such as WebConfig, DataJpaConfig etc. A full featured configuration(mixed web, data, security etc) also caused your test slice based tests to be failed. Check the test samples in my sample.

It work fo me

the package name of the above test class is changed to the same as the package name of the normal class.

change to this


I think that the best solution for this issue is to align your tests folders structure with the application folder structure.

I had the same issue which was caused by duplicating my project from a different folder structure project.

if your test project and your application project will have the same structure you will not be required to add any special annotations to your tests classes and everything will work as is.


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;



@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest
@AutoConfigureWebMvc
public class RepoTest {

    @Autowired
    private ThingShiftDetailsRepository thingShiftDetailsRepo;

    @Test
    public void findThingShiftDetails() {
            ShiftDetails details = new ShiftDetails();
            details.setThingId(1);

            thingShiftDetailsRepo.save(details);

            ShiftDetails dbDetails = thingShiftDetailsRepo.findByThingId(1);
            System.out.println(dbDetails);
    }
}

Above annotations worked well for me. I am using spring boot with JPA.

참고URL : https://stackoverflow.com/questions/39084491/unable-to-find-a-springbootconfiguration-when-doing-a-jpatest

반응형