SpringBoot 测试及 MockMvc的使用

1. @SpringBootTest 单元测试


1. 添加依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
2. 添加测试类
package com.test.spring_boot_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) // 底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes = {SdSpringBootApplication.class}) // 启动整个SpringBoot工具
public class SpringBootDemoTest {

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

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

    @Before
    public void testBefore() {
        System.out.println("before");
    }

    @After
    public void testAfter() {
        System.out.println("after");
    }

}
3. 运行测试
  • 如果测试某个方法,直接运行要测试的方法。
  • 如果测试类中的多个方法,直接运行测试类。

2. MocMvc(模拟MVC请求,实现接口测试)


1. 添加测试接口(Controller)
@GetMapping("/test/home")
public String testHome() {
    return "test home ...";
}
2. 添加测试类
package com.test.spring_boot_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.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 = {SdSpringBootApplication.class})
@AutoConfigureMockMvc
public class MockMvcDemoTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void apiTest() throws Exception {
        // perform: 执行一个 RequestBuilder 请求
        // andExpect: 添加 ResultMatcher -> MockMvcResultMatchers 验证规则
        // andReturn: 最后返回相应的 MvcResult
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/home")).
                andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        int status = mvcResult.getResponse().getStatus();
        System.out.println(status);
    }

}

转载于:https://my.oschina.net/shadowolf/blog/1841323

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值