【问题标题】:How do do slice testing in Spring Boot 1.4 using @DataJpaTest with SpringFox @EnableSwagger2如何在 Spring Boot 1.4 中使用 @DataJpaTest 和 SpringFox @EnableSwagger2 进行切片测试
【发布时间】:2017-05-31 02:24:38
【问题描述】:

回复:https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

我尝试使用@DataJpaTest 测试我的存储库,但我的应用程序使用的是 Springfox,因此使用 Springfox @EnableSwagger2 测试执行将失败并出现以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
...    
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<org.springframework.web.servlet.mvc.method.requestmappinginfohandlermapping>' available

可以做些什么来解决这个问题?否则无法使用@DataJpaTest 进行切片测试。

代码:

Application class:
@SpringBootApplication
@EnableSwagger2
public class CurrencyApplication {
  @Bean
  public Module datatypeHibernateModule() {
    return new Hibernate5Module();
  }

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

  @Bean
  public Docket currencyApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()
        .pathMapping("/")
        ;
  }
}

测试类:

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

  @Test
  public void doNothing() {
  }
}

【问题讨论】:

  • 我不确定您在尝试什么。请分享一些代码。在进行切片测试时不要尝试加载所有弹簧上下文。这可以通过删除 @SpringBootTest 来完成

标签: java spring spring-boot springfox


【解决方案1】:

将@EnableSwagger 移出SpringBootApplication

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

@Configuration
@EnableSwagger2
class AdditionalConfig {

}

【讨论】:

  • 也适用于@DataMongoTest。请注意,如果您有其他 @Enable* 注释,最好也将它们移至 Config 类。
  • 拯救了这一天!非常感谢
  • 我在使用@DataJpaTest 进行测试时遇到了问题,因此。在尝试运行测试时,我收到了 No ServletContext set 错误。一个相当模糊的信息。你的回答成功了。我把这个放在这里是为了在谷歌搜索如何解决同样的问题时帮助其他人......我花了 2 个小时来解决这个问题。非常感谢
猜你喜欢
  • 2016-10-31
  • 2018-01-25
  • 2023-03-23
  • 2021-11-30
  • 2019-03-28
  • 2016-10-29
  • 2016-11-05
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多