博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot快速入门
阅读量:4618 次
发布时间:2019-06-09

本文共 1986 字,大约阅读时间需要 6 分钟。

引入Web模块

当前的pom.xml内容如下,仅引入了两个模块:

  • spring-boot-starter:核心模块,包括自动配置支持、日志和YAML
  • spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test

引入Web模块,需添加spring-boot-starter-web模块:

org.springframework.boot
spring-boot-starter-web

编写HelloWorld服务

  • 创建package命名为com.didispace.web(根据实际情况修改)
  • 创建HelloController类,内容如下
@RestController public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } }
  • 启动主程序,打开浏览器访问http://localhost:8080/hello,可以看到页面输出Hello World

编写单元测试用例

打开的src/test/下的测试入口Chapter1ApplicationTests类。下面编写一个简单的单元测试来模拟http请求,具体如下:

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class Chapter1ApplicationTests { private MockMvc mvc; @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new HelloController()).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"))); } }

使用MockServletContext来构建一个空的WebApplicationContext,这样我们创建的HelloController就可以在@Before函数中创建并传递到MockMvcBuilders.standaloneSetup()函数中。

  • 注意引入下面内容,让statuscontentequalTo函数可用
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;

至此已完成目标,通过Maven构建了一个空白Spring Boot项目,再通过引入web模块实现了一个简单的请求处理。

转载于:https://www.cnblogs.com/xuyatao/p/8269683.html

你可能感兴趣的文章
create-react-app 配置sass
查看>>
02_关系数据库
查看>>
在win7电脑中如何查看运行进程的PID标识符
查看>>
[Vue] vue-cli3.0安装
查看>>
shell中如何进行算术运算
查看>>
为什么所有的架构都是糟糕的
查看>>
PageControl的小点点随ScrollView滑动而变动代码
查看>>
(十三)在ASP.NET CORE中使用Options
查看>>
关于博主
查看>>
贝叶斯规则
查看>>
解决Centos/Redhat,命令不存在
查看>>
项目实战—小饭桌
查看>>
ArrayList深拷贝的一种实现方法
查看>>
2012考研英语--前辈的高分复习经验
查看>>
UVA10603倒水问题+隐式图搜索
查看>>
C++学习之字符串
查看>>
图像化列表
查看>>
2014年10月9日——语言基础2
查看>>
mysql查
查看>>
[正则表达式]难点和误区
查看>>