若依SpringBoot添加单元测试类及测试类启动报错

发表于:2024-2-06 09:45

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:天天++    来源:CSDN

  一、添加测试类的依赖
  在admin 模块中添加单元测试,将以下依赖添加到 admin 的 pom.xml 中。
          <!--测试类-->
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <scope>test</scope>
          </dependency>
          <!--测试类-->
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-test</artifactId>
              <scope>test</scope>
          </dependency>
          <!--测试类-->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-test</artifactId>
              <scope>test</scope>
          </dependency>
  二、编写测试类
  在 src 目录下创建 test.java.MainTests 文件:
  import com.ruoyi.RuoYiApplication;
  import com.ruoyi.activity.domain.Activity;
  import com.ruoyi.activity.mapper.ActivityMapper;
  import org.junit.Test;
  import org.junit.runner.RunWith;
  import org.mybatis.spring.annotation.MapperScan;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.boot.test.context.SpringBootTest;
  import org.springframework.test.context.junit4.SpringRunner;
  import java.util.List;
  @RunWith(SpringRunner.class)
  @SpringBootTest(classes = RuoYiApplication.class)
  public class MainTests {
      @Autowired
      private ActivityMapper activityMapper;
      @Test
      public void testSelectActivityById() {
          Activity activity = activityMapper.selectActivityById(1);
          System.out.println(activity);
      }
      @Test
      public void testSelectActivityList() {
          List<Activity> activityList = activityMapper.selectActivityList(new Activity());
          System.out.println(activityList);
      }
      
  }
  三、Spring Boot 加入websocket后,单元测试启动报错(javax.websocket.server.ServerContainer not available)
  错误提示:
  java.lang.IllegalStateException: Failed to load ApplicationContext
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘serverEndpointExporter’ defined in class path resource [com/zou/sell/config/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available
  解决方案:
  在springbootTest注解加入 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,我们在测试使用 websocket的时候需要启动一个完整的服务器,而使用这个注解就是说每次测试都会选用一个随即可用的端口模拟启动一个完整的服务器。
  @SpringBootTest(classes = RuoYiApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号