package cn.edu.tju.se;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.core.JsonProcessingException;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TjuProjectApplication.
class)
@WebAppConfiguration
public class test {
MockMvc mvc;
@Autowired
WebApplicationContext webApplicationConnect;
String expectedJson;
@Before
public void setUp()
throws JsonProcessingException {
mvc =
MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
}
@Test
public void show()
throws Exception
{
String responseString =
mvc.perform
(
get("/api/products")
//请求的url,请求的方法是get
)
.andExpect(status().isOk()) //返回的状态是200
.andDo(print())
//打印出请求和相应的内容
.andReturn().getResponse().getContentAsString();
//将相应的数据转换为字符串
System.out.println("-----返回的json = " +
responseString);
}
}
转载于:https://www.cnblogs.com/LandingGuy/p/11371446.html