单元测试--SpringbootTest和MockMvc


SpringbootTest

基于Junit 的Test

import junit.framework.TestCase;
import org.junit.Assert;
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)    //底层用junit的 SpringJUnit4ClassRunner
@SpringBootTest(classes = {XdclassSpringbootApplication.class})
public class XdclassSpringbootApplicationTests {

    @Test
    public void testOne() {
        System.out.println("start test");
        Assert.assertEquals(1,1);
        TestCase.assertEquals(1,2);
    }

}

 

  • 当然也可以使用 @Before 和 @After , 和 junit 的测试一样。

  • 启动类是必须要有的。

  • 当有多个 @Test 的方法,需要一起执行的时候, 执行 

    XdclassSpringbootApplicationTests 这个类的 run或debug。

  • Assert 和 TestCase 都是 断言,用法一样。

 

MockMvc类的使用和模拟Http请求

相关API:

  • perform:执行一个RequestBuilder请求

  • andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则

  • andReturn:最后返回相应的MvcResult->Response

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
@AutoConfigureMockMvc
public class MockMvcTestDemo {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void apiTest(){
        try {
            MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn(); }
catch (Exception e) { e.printStackTrace(); } } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM