首页 文章

在执行JpaTest时无法找到@SpringBootConfiguration

提问于
浏览
107

我是框架的新手(刚刚通过了这个类),这是我第一次使用springboot .

我正在尝试运行一个简单的Junit测试来查看我的CrudRepositories是否确实正常工作 .

我一直得到的错误是:

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

不 spring 启动配置自己?

我的测试班

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

 }

我的Spring启动应用启动器

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

    }
}

提前致谢

7 回答

  • 9

    实际上,Spring Boot确实在很大程度上确立了自己的地位 . 你可能已经摆脱了很多你发布的代码,尤其是 Application .

    我希望你已经包含了所有类的包名,或者至少包含 ApplicationJpaTest 的包名 . 关于 @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);
        }
    }
    

    其次是 JpaTest.java 的内容:

    package com.example.test;
    
    @RunWith(SpringRunner.class)
    @DataJpaTest
    public class JpaTest {
    
        @Test
        public void testDummy() {
        }
    }
    

    一切都应该有效 . 如果在 src/main/com/example 中创建一个名为 app 的新文件夹,然后将 Application.java 放入其中(并更新文件中的 package 声明),运行测试将会出现以下错误:

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

  • 0

    配置附加到应用程序类,因此以下将正确设置所有内容:

    @SpringBootTest(classes = Application.class)
    

    JHipster项目的示例here .

  • 6

    值得检查是否已使用 @SpringBootApplication 注释的主类的重构包名称 . 在这种情况下,测试用例应该在适当的包装中,否则它将在较旧的包装中寻找它 . 这就是我的情况 .

  • 52

    除了ThomasKåsene所说的,你还可以添加

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

    如果您不想重构文件层次结构,则指向测试注释以指定其应该查找其他类的位置 . 这是错误消息提示的内容:

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

  • 0

    Spring Boot 1.4中提供的 test slice 带来了面向 feature 的测试功能 .

    例如,

    @JsonTest 提供了一个简单的Jackson环境来测试json序列化和反序列化 .

    @WebMvcTest 提供了一个模拟Web环境,它可以指定用于测试的控制器类,并在测试中注入MockMvc .

    @WebMvcTest(PostController.class)
    public class PostControllerMvcTest{
    
        @Inject MockMvc mockMvc;
    
    }
    

    @DataJpaTest 将准备一个嵌入式数据库,并为测试提供基本的JPA环境 .

    @RestClientTest 为测试提供REST客户端环境,尤其是RestTemplateBuilder等 .

    这些注释不是由SpringBootTest组成的,它们与一系列 AutoconfigureXXX@TypeExcludesFilter 注释相结合 .

    看看 @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 {}
    

    您可以添加@AutoconfigureXXX注释以覆盖默认配置 .

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

    我们来看看你的问题,

    • 不要混合 @DataJpaTest@SpringBootTest ,如上所述 @DataJpaTest 将以自己的方式构建配置(例如,默认情况下,它将尝试从应用程序配置继承中准备嵌入式H2) . @DataJpaTest 指定为 test slice .

    • 如果要自定义 @DataJpaTest 的配置,请阅读Spring.io的this official blog entry以获取此主题,(有点单调乏味) .

    • WebConfigDataJpaConfig 等功能将 Application 中的配置拆分为较小的配置 . full featured configuration (混合网络,数据,安全等)也导致基于 test slice 的测试失败 . 检查my sample中的test samples .

  • 162
    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);
        }
    }
    

    以上注释对我来说效果很好 . 我正在使用JPA的 Spring 季靴子 .

  • 1

    我认为这个问题的最佳解决方案是将测试文件夹结构与应用程序文件夹结构对齐 .

    我有同样的问题,这是由于从不同的文件夹结构项目复制我的项目造成的 .

    如果您的测试项目和您的应用程序项目具有相同的结构,则不需要向测试类添加任何特殊注释,一切都将按原样工作 .

相关问题