美文网首页
SpringBoot系列二:添加Restful API

SpringBoot系列二:添加Restful API

作者: kentwu | 来源:发表于2017-02-28 16:47 被阅读0次

1 在build.gradle中添加依赖

compile('org.springframework.boot:spring-boot-starter-web')

2 添加DemoController类


图1 目录结构
@RestController
public classDemoController {
    @RequestMapping("/hello")
    public ResponseEntity sayHello() {
        returnResponseEntity.ok("Hello World!");
    }
}

3 添加API的测试

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoControllerTests {

    @Autowired
    private TestRestTemplate testRestTemplate;
    
    @Test
    public void should_return_hello_world() {
        ResponseEntity<String> entity = testRestTemplate.getForEntity("/hello", String.class);
        assertThat(entity.getBody()).isEqualTo("Hello World!");
    }

}

4 运行测试


图2 测试通过

5 使用postman测试
除了写junit测试,我们当然还可以将程序运行起来,然后使用postman去测试接口是否可用。

图3 使用postman测试

**示例代码:https://github.com/kent-wu/springBootDemo.git

相关文章

网友评论

      本文标题:SpringBoot系列二:添加Restful API

      本文链接:https://www.haomeiwen.com/subject/wogxgttx.html