【问题标题】:Exclude a configuration when @WebMvcTest in Spring Boot 1.4在 Spring Boot 1.4 中排除 @WebMvcTest 时的配置
【发布时间】:2016-12-20 05:24:06
【问题描述】:

我在java/ 目录(相同的包)中有一个@SpringBootApplication 类,在test/ 中有另一个@SpringBootApplication 类,用于模拟一些自动连接的bean。有几个测试,使用的配置因测试而异。

在测试类中

@RunWith(SpringRunner.class)
@WebMvcTest(RecApiServerController.class)

抛出

java.lang.IllegalStateException: Found multiple @SpringBootConfiguration annotated classes [Generic bean: class [com.xxx.MockedTestConfig]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/..direction.../target/test-classes/com/xxx/MockedTestConfig.class], Generic bean: class [com.xxx.MyApplication]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/...direction.../target/classes/com/xxx/MyApplication.class]]

我只是想测试一个控制器的路由。

如何设置特定的应用程序配置?

【问题讨论】:

    标签: spring spring-boot spring-mvc-test


    【解决方案1】:

    您不能在同一个包中包含两个 @SpringBootConfiguration (@SpringBootApplication)。 @WebMvcTest 自动为您搜索配置源(请参阅the doc)。如果您想调整事物但不能在同一个包中包含两个,则可以在测试的嵌套包中包含一个特殊的 @SpringBootConfiguration(或应用程序)。

    我不确定文档是否对此非常明确,因此我们可能应该澄清一下。

    无论如何,自定义@SpringBootApplication 和切片有点奇怪。 @SpringMvcTest 已经只负责启用必要的功能。如果你想模拟一些 bean,你应该@SpringBootApplication 中定义它。您导入的常规@Configuration 很好。我们还有@MockBean 可以自动为您模拟。

    【讨论】:

    • 我将MockedTestConfig.class 更改为常规@Configuration 并在@SpringBootTest 中添加classes = { MyApplication.class, MockedTestConfig.class },所有测试都运行良好。他们以前没有,所以我把它改成了@SpringBootApplication。我认为当时classes 的顺序是错误的。谢谢你。 :)
    猜你喜欢
    • 2016-11-05
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多