1 在build.gradle中添加依賴
compile('org.springframework.boot:spring-boot-starter-web')
2 添加DemoController類
圖1 目錄結(jié)構(gòu)
@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測試奏属,我們當(dāng)然還可以將程序運行起來,然后使用postman去測試接口是否可用乾颁。
圖3 使用postman測試