SpringBoot—單元測試模板(controller層和service層)

介紹

概述

  在開發過程中,我們經常會一股腦的寫各種業務邏輯,經常等全部大功告成的時候,打個jar包放環境裏跑跑看看能不能通,殊不知在各個業務方法中已經漏洞百出,修復一個打一個包,再繼續修復,這種效率真的太低下。
  所以我們需要藉助一些單元測試來將我們寫的代碼做一些測試,這樣保證局部方法正確,最後再打包整體運行將整個流程再串起來就能提高開發試錯效率。當然,我們除了單元測試,我們還可以通過main()方法在每個類中進行測試,文中會一帶而過。

常用註解

  • @RunWith(SpringRunner.class):測試運行器,作用類
  • @SpringBootTest:SpringBoot測試類,作用類
  • @Test:測試方法,作用方法
  • @Ignore:忽略測試方法,作用方法
  • @BeforeClass:針對所有測試,只執行一次,且必須爲static void
  • @Before:初始化方法,執行當前測試類的每個測試方法前執行
  • @After:釋放資源,執行當前測試類的每個測試方法後執行
  • @AfterClass:針對所有測試,只執行一次,且必須爲static void

作者:hadoop_a9bb
鏈接:https://www.jianshu.com/p/81fc2c98774f
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

模板

依賴

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

spring-boot-starter-test 內部包含了junit功能。

controller層單元測試模板

controller層示例

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author Andya
 * @create 2020-04-22 22:41
 */

@RestController
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello";
    }
}

controller層單元測試類

import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Andya
 * @create 2020-06-02 13:59
 */
public class HelloControllerTest {

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception{
        mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }

    @Test
    public void getHello() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

}

service層單元測試模板

service層示例

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Andya
 * @create 2020-06-01 9:30
 */
@Service
public class TwoSum {

    public static int[] twoSum1(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap();
        for (int i = 0; i < nums.length; i++){
            map.put(nums[i], i);
        }
        System.out.println(map);
        for (int i = 0; i < nums.length; i++) {
            int result = target - nums[i];
            if(map.containsKey(result) && map.get(result) != i) {
                return new int[] {i,map.get(result)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    public static int[] twoSum(int[] nums, int target) {

        for (int i = 0; i < nums.length; i++){
            for(int j = i+1; j < nums.length;j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;

    }

    public static int[] twoSum2(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            //計算結果
            int result = target - nums[i];
            //map中是否包含這個結果,若包含則返回該結果,及對應的目前數組的index
            if (map.containsKey(result)) {
                //map是後添加元素的,所以map索引在前,i在後
                return new int[]{map.get(result), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("no two sum solution");
    }
}

service層單元測試類

import com.example.andya.demo.service.algorithm.TwoSum;
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.SpringRunner;

/**
 * @author Andya
 * @create 2020-06-02 14:36
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class TwoSumTest {
    @Autowired
    TwoSum twoSum;

    @Test
    public void testSum1(){
        int[]  nums = new int[] {1,1,3};
        int[] newNums = twoSum.twoSum1(nums,2);
        System.out.println(newNums[0] + ":" +newNums[1]);
    }

    @Test
    @Ignore
    public void testSum2() {
        int[]  nums = new int[] {2,2,4};
        int[] newNums = twoSum.twoSum2(nums,4);
        System.out.println(newNums[0] + ":" +newNums[1]);
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章