SpringBoot系列二:添加Restful API

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容