一、环境
开发工具:IDEA2018.2
系统:win10
JDK1.8
maven3.5.4
后续文章的开发环境默认使用上述环境。
二、创建工程
打开IDEA,菜单栏选择“File->New->Project":
“Project SDK”: 选择JDK安装路径。
“Initial Service Url”: 默认指向的地址就是Spring官方提供的Spring Initializr工具地址,所以这里创建的工程实际上也是基于它的Web工具来实现的。
点击“Next”:
填入项目信息,点击"Next",
选择“web",spring boot版本使用默认的release版本,点击"Next",
在这里,可以修改项目名和项目存储路径,点击"Finish",等待项目构建。
项目构建完成后, 项目结构如下图示:
创建一个控制类HelloController.class:
package hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value="/helo")
public String index() {
return "Hello Spring!";
}
}
说明:“/helo”是访问路径。
三、编译运行
编译工程,运行项目。运行成功的打印日志:
然后,在浏览器打开http://localhost:8080/helo:
“8080”是默认的监听端口,也可以自定义,在application.properties文件中加一句:
server.port=8081
重新编译并运行工程,在浏览器打开http://localhost:8081/helo:
四、编写单元测试
- 编写测试用例
打开src/test/DemoApplicationTests.java文件:
package hello;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
编辑该文件:
package hello;
import hello.test.HelloController;
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 static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.Matchers.equalTo;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
private MockMvc mvc;
@Before
public void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void contextLoads() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/helo").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello Spring!")));
}
}
- 运行测试用例
点击函数“contextLoads” 左边的红色三角形,选择“Run contextLoads()”:
如果测试用例通过测试,控制台会显示“Tests passed”:
五、参考
本文参考:
http://blog.didispace.com/spring-boot-learning-1/
https://spring.io/guides/gs/rest-service/