1 在build.gradle中添加依赖
compile('org.springframework.boot:spring-boot-starter-web')
2 添加DemoController类
@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 运行测试
5 使用postman测试
除了写junit测试,我们当然还可以将程序运行起来,然后使用postman去测试接口是否可用。