单元测试时报错

java.lang.IllegalStateException: Failed to load ApplicationContext

原代码

原代码

@SpringBootTest(classes = AdminApplication.class)
@RunWith(SpringRunner.class)

修改后

@SpringBootTest(classes = AdminApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)

解决方法

  • 第一种方式:去掉测试类的

@RunWith(SpringRunner.class)

去掉即可,但是这种方式会有局限,比如下方你要@Authwired一个类的时候会报错,我这里不可以,根据你的代码情况。

  • 第二种方式:在SpringBootTest后加上:

webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT

,意思是创建Web应用程序上下文(基于响应或基于servlet),原因:websocket是需要依赖tomcat等容器的启动。所以在测试过程中我们要真正的启动一个tomcat作为容器。

转载 https://blog.csdn.net/weixin_40936211/article/details/89466144

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐