在SpringBoot中测试表现层接口一般常用Airport、PostMan,也可在原代码基础上进行虚拟测试接口:

1.新建Test表现层代码接口:

 1 @RestController
 2 @RequestMapping("/look")      *测试用的接口
 3 public class GetController {
 4     @GetMapping
 5     public String getById(){
 6         System.out.println("hhhh is running");
 7         return "SpringBoot";                      
 8     }
 9 
10 }

2.在Test中加入注解

//开启虚拟调用Mvc

@AutoConfigureMockMvc  

3.自动装配

    @Autowired
    private MockMvc mvc;

4.

    @Test
    void printUrl() throws Exception {
        System.out.println(url);
        System.out.println(msg);
        //创建虚拟请求,通过get获取表现层"/look"
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/look");
        //Mvc的功能调用
        ResultActions actions = mvc.perform(builder);
        //定义状态匹配器
        StatusResultMatchers status= MockMvcResultMatchers.status();
        //定义预期执行状态
        ResultMatcher ok= status.isOk();
        //本次真实执行结果与预期执行结果对比
        actions.andExpect(ok);
    }

5.完成。

如果没有Mvc服务可采取在pom中加入注解

       <!--开启web服务            -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

 

posted on 2022-10-03 17:03  园来个园  阅读(25)  评论(0)    收藏  举报