建立过程如下:
一、环境准备:
- 安装JDK环境,自行搜索网络教程。
- 下载并安装Maven。
- 下载并安装STS。下载网址:https://spring.io/tools/sts/all/
二、搭建helloworld项目
1.选择创建springboot向导
路径:file->new->spring start project
选择WEB特性,新建一个SpringBoot项目,
2.在pom.xml文件中存在以下依赖。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
3.创建HelloWorldController类
@RestController public class HelloWorldController { @RequestMapping("/hello") public String index() { return "Hello World"; } }
4.运行HelloWorldApplication类,启动服务
5.浏览器输入http://127.0.0.1:8080/hello
6.界面输出helloworld
项目搭建成功。
三、测试
创建测试类,打印执行结果
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration public class HelloWorldControlerTests { 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(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); } }
结果:
MockHttpServletRequest: HTTP Method = GET Request URI = /hello Parameters = {} Headers = {Accept=[application/json]} Handler: Type = com.example.demo.HelloWorldController Method = public java.lang.String com.example.demo.HelloWorldController.index() Async: Async started = false Async result = null Resolved Exception: Type = null ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[15]} Content type = application/json;charset=ISO-8859-1 Body = Hello World LJZ Forwarded URL = null Redirected URL = null Cookies = []
时间: 2024-10-31 08:10:15