错误:为Spring Controller执行@WebMvcTest时找不到@SpringBootConfiguration

错误:为Spring Controller执行@WebMvcTest时找不到@SpringBootConfiguration,第1张

错误:为Spring Controller执行@WebMvcTest时找不到@SpringBootConfiguration

所以这是解决方案:

有关检测测试配置的文档说:

搜索算法从包含测试的程序包开始工作,直到找到@SpringBootApplication或@SpringBootConfiguration注释的类。只要您以合理的方式构造代码,通常就可以找到您的主要配置。

因此,

@SpringBootApplication
该类在包层次结构中应比测试类高,例如,如果测试类在包中,
com.zerosolutions.controller
@SpringBootApplication
该类应在比
com.zerosolutions.controller
包ie
com.zerosolutions
或 更高的包中
com

问题

但是,如果

@SpringBootApplication
该类与测试类处于同一级别,则无法找到它,即
com.zerosolutions.general
。在这种情况下,您将收到以下错误:

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

如果您正在运行集成测试,则可以显式提及

@SpringBootApplication
此类

@RunWith(SpringRunner.class)@SpringBootTest(classes={SpringBootApp.class})

但是,如果要对控制器进行单元测试,则无需启动整个Spring上下文。您可以替换

@SpringBootTest
@WebMvcTest(MasterController.class)
。这将仅实例化具有Web层的Web层,
MasterController
而不实例化整个Spring上下文。

问题

但是问题是您将再次遇到我们之前遇到的错误:

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

并且

@WebMvtTest
没有
classes
喜欢
@SpringBootTest
明确提及
@SpringBootApplication
该类的属性。因此,有两种解决方案。

第一 :将您的应用程序类移到比测试类(即

com.zerosolutions
com
包)高的包中。

第二

@SpringBootApplication
像下面这样明确提及您的班级

@RunWith(SpringRunner.class)@WebMvcTest(MasterController.class)@ContextConfiguration(classes={SpringBootApp.class})

希望这可以消除Spring Test Configuration的困惑。谢谢



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5046055.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-15
下一篇2022-11-15

发表评论

登录后才能评论

评论列表(0条)

    保存