Spring boot 1.4.2 单元测试配置

直接主题,新版较旧版简化了很多

直接在测试类上添加如下注解

  @RunWith(SpringRunner.class)
@SpringBootTest(classes = 自己的启动类, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

同时注入 TestRestTemplate类:

TestRestTemplate类包含了post、get、put、delete等方法,不同方法调用不同接口即可。

通过 @LocalServerPort注解,获取测试时动态的端口号

具体测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

    @LocalServerPort
    private int port;

    private URL base;
    private Gson gson = new Gson();

    @Autowired
    private TestRestTemplate restTemplate;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @Test
    public void test() {
        ResponseEntity<String> test = this.restTemplate.getForEntity(
                this.base.toString() + "/task", String.class, "test");
        System.out.println(test.getBody());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容