欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单元测试二、对controller层

程序员文章站 2022-03-02 18:06:25
...

1.加入pom依赖

<dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
     <scope>test</scope>
</dependency>

2.在application.properties加入扫描文件

<context:component-scan base-package="com.junittestdemo.demo" />

3. 编写controller的类

package com.junittestdemo.demo.controller;

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

/**
 * package:com.junittestdemo.demo.controller
 *
 * @date:2020/4/16 17:20
 * @author:Yaoxiaoming
 **/
@RestController
public class StudentContoller {
    @RequestMapping("/hello")
    public String Helloworld(){
        return "hello king";
    }
}

4.编写controller测试类

package com.junittestdemo.demo.controller;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpMethod;
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;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

/**
 * package:com.junittestdemo.demo.controller
 *
 * @date:2020/4/17 8:37
 * @author:Yaoxiaoming
 **/
@SpringBootTest
class StudentContollerTest {

    //mock对象
    private MockMvc mockMvc;

    @BeforeEach
    void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(new StudentContoller()).build();
    }

    @Test
    void helloworld() {
        try {
            MvcResult result = mockMvc.perform(
                    MockMvcRequestBuilders.request(HttpMethod.GET, "/hello"))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andDo(print())
                    .andReturn();;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5.运行以后,就可以访问hello world了