1. 程式人生 > >Springboot2.x單元測試

Springboot2.x單元測試

autowired expec mvc sts 斷言 actor 增加 默認 uil

簡介:講解SpringBoot的單元測試
1、引入相關依賴
<!--springboot程序測試依賴,如果是自動創建項目默認添加-->

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

2、使用
@RunWith(SpringRunner.class) //底層用junit SpringJUnit4ClassRunner


@SpringBootTest(classes={DemoApplication.class})// 指定啟動類,啟動整個springboot工程

package net.nbclass.demo;

import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = {DemoApplication.class}) public class DemoApplicationTests { @Test public void contextLoads() { System.out.println("測試中1"); // 斷言 TestCase.assertEquals(1,1); } @Test
public void contextLoads1() { System.out.println("測試中2"); TestCase.assertEquals(1,1); } @Before public void testBefore(){ System.out.println("測試前"); } @After public void testAfter(){ System.out.println("測試後"); } }

單獨測試只需要運行對應的@test註解的方法就可以,全部測試就運行DemoApplicationTests 類就可以了

以下是測試API的,增加類註解 @AutoConfigureMockMvc

package net.nbclass.demo;

import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
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.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {DemoApplication.class})
@AutoConfigureMockMvc  //測試接口用
public class DemoApplicationTests {
  
    @Before
    public void testBefore(){
        System.out.println("測試前");
    }

    @After
    public void testAfter(){
        System.out.println("測試後");
    }

    //下面是測試接口
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void apiTest()throws Exception{
        MvcResult mvcResult=mockMvc.perform(MockMvcRequestBuilders.get("/get")).
                andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        int status=mvcResult.getResponse().getStatus();                              ----打印出狀態碼,200就是成功
        System.out.println(status);
    }

}

Springboot2.x單元測試