SpringBoot中使用mock进行单元测试无法导入mock方法,例如status()、content()、equalTo()方法

SpringBoot中使用mock进行单元测试无法导入mock方法,例如status()、content()、equalTo()方法,记录一下。

HelloTests类代码
package com.neo.SpringBoot;

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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.neo.SpringBoot.controller.HelloWorldController;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloTests {

private MockMvc mvc;

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

@Test
public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(equalTo("Hello World")));
}

}

HelloWorldController类代码
package com.neo.SpringBoot.controller;

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

@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String index() {
return “Hello World”;
}
}

需要导入的方法
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

https://blog.csdn.net/ththcc/article/details/81132958

猜你喜欢

转载自blog.csdn.net/qq_32692795/article/details/87861768