Springboot2.x單元測試


簡介:講解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);
    }

}

 


免責聲明!

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



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