使用MockMvc模拟Http请求

2023-04-27 15:44:51 浏览数 (1)

代码语言:javascript复制
package com.qicong.sboot;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
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 org.springframework.web.context.WebApplicationContext;

/**
 * User: 祁大聪
 */
@SpringBootTest
publicclass S10MockMvcTests {

    MockMvc mockMvc;//模拟http请求

    @Autowired
    WebApplicationContext context;

    @BeforeEach
    publicvoid setup(){
        mockMvc =MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    publicvoid testIndex()throwsException{
        String result = mockMvc.perform(MockMvcRequestBuilders.get("/s08/index"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println("result = "  result);
    }

}

0 人点赞