SpringBoot单元测试踩坑

今天写了一个算法,需要用单元测试来测试其效果。

后端使用SpringBoot框架

pom文件导入依赖如下

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>                    

Test类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BPNNTest {

    @Autowired
    private TestService service;

    @Test
    public void test1() {
        service.estimateTime();
    }
}

在测试过程中遇到了几个问题,记录如下

报错一:

java.lang.NoClassDefFoundError: org/springframework/core/annotation/MergedAnnotations

查找资料后发现原因是之前引入的依赖问题,

        <!--原先的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.1.RELEASE</version>
            <scope>compile</scope>
        </dependency>

解决方案就是将版本降低至5.0.2.RELEASE或者删掉该依赖,仅用spring-boot-starter-test即可。

报错二:

Error creating bean with name 'methodValidationPostProcessor'
...
Error resolving JdbcType. Cause: java.lang.IllegalArgumentException: No enum constant org.apache.ibatis.type.JdbcType.DOUBLEE

该报错尾部提示类型不对,将相应类型改为正确类型即可

报错三:

javax.websocket.server.ServerContainer not available

查找资料后发现SpringBootTest在启动时不会启动服务器,所以websocket会报错,需提供一个测试的web环境

解决方案就是在@SpringBootTest注解内添加webEnvironment属性

@SpringBootTest(classes = MyApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
原文地址:https://www.cnblogs.com/MrZhaoyx/p/13271828.html