IDEA中SpringBoot項目快速創建單元測試


如何在IDEA中對於SpringBoot項目快速創建單元測試

創建測試用例

image

右鍵需要進行測試的方法,選擇GO TO然后選擇Test

image

點擊Create New Test

image

勾選需要創建單元測試的方法

然后點擊OK就直接創建完成了。

 

修改測試用例

在類上面加上注解

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
然后在下面注入需要測試的類然后在方法里面使用,使用方法和普通的單元測試一樣
如果測試的是service
demo如下
package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class HelloServiceTest {

    @Autowired
    private HelloService helloService;

    @Test
    public void hello(){
        helloService.hello();
    }

}

 

如果測試的是controller

需要加入@AutoConfigureMockMvc的注解

那么demo如下

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void hello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }

}

其中對於MockMvc的使用可以自己研究一下,里面有很多測試使用的東西,這邊只是舉個例子,只要訪問是200不是404這種錯誤都會過測試用例


免責聲明!

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



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