1. 打开HelloWorldApplicationTests.java文件
默认情况下系统应自动创建该文件,位置如下:
2. 添加@RunWith(SpringRunner.class)和@SpringBootTest注解
@RunWith(SpringRunner.class)和@SpringBootTest注解,表明被注解的类是测试类。
为测试环境指定随机端口:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
如下:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldApplicationTests {
... ...
}
3. 定义TestRestTemplate
TestRestTemplate为RestTemplate的测试类,RestTemplate用于远程调用HTTP API接口。
4. 导入静态类org.assertj.core.api.Assertions.*
导入Assertions是为了使用assertThat(…).isEqualTo("…")方法
5. 完整代码如下:
package com.hawkeye.helloworld;
import org.junit