使用springboot写一个简单的测试用例

使用springboot写一个简单的测试用例

使用springboot写一个简单的测试用例

目录结构

使用springboot写一个简单的测试用例_第1张图片

pom



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
         
    
    test
    test
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot

    
        UTF-8
        UTF-8
        1.8
    

    

        
            org.springframework.boot
            spring-boot-starter-web
            2.0.5.RELEASE
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

TestController

package test.test.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    @ResponseBody
    @RequestMapping(value = "/helloword", method = RequestMethod.GET)
    public String home() {
 
        return "Hello World!!!";
    }
}

DemoApplicationTests

package test.test;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

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

import static org.hamcrest.Matchers.equalTo;

import test.test.controller.TestController;

@RunWith(SpringRunner.class)
@WebAppConfiguration // 开启web应用配置
@SpringBootTest
public class DemoApplicationTests {
    private MockMvc mvc;

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

    @Test
    public void hello() throws Exception {
        mvc.perform(
            MockMvcRequestBuilders
            .get("/helloword")
            .accept(MediaType.APPLICATION_JSON_UTF8)
        )
        .andExpect(status().isOk()) // 用于判断返回的期望值
        .andExpect(content().string(equalTo("Hello World!!!")));
        
    }   
}
posted @ 2019-01-19 21:51 qz奔跑的马 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(使用springboot写一个简单的测试用例)