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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM