上QQ阅读APP看书,第一时间看更新
4.2.3 Spring Boot的测试
Spring Boot开启测试也非常简单,只需要加@RunWith(SpringRunner.class)和@SpringBootTest注解,在@SpringBootTest注解加上Web测试环境的端口为随机端口的配置。TestRestTemplate类为RestTemplate测试类,RestTemplate用于远程调用Http API接口。测试代码如下:
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloControllerIT { @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate template; @Before public void setUp() throws Exception { this.base = new URL("http://localhost:" + port + "/hello"); } @Test public void getHello() throws Exception { ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); assertThat(response.getBody(), equalTo("Greetings from Spring Boot!")); } }
启动测试类的getHello() 方法,通过控制台可以发现Spring Boot程序会先启动,然后运行测试代码,最后测试通过。