JAVA spring boot 微服务快速上手(02)

1. 打开HelloWorldApplicationTests.java文件

默认情况下系统应自动创建该文件,位置如下:
JAVA spring boot 微服务快速上手(02)_第1张图片

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.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.assertj.core.api.Assertions.*;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldApplicationTests {
    @LocalServerPort
    private int port;
    private URL baseURL;

    @Autowired
    private TestRestTemplate template;

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

    @Test
    public void getHi() throws Exception {
        ResponseEntity<String> response = template.getForEntity(baseURL.toString(),
                String.class);
        assertThat(response.getBody()).isEqualTo("hi, this is hawkzy's program");
    }

}

注意上面的断言assertThat().isEqualTo()中间的"hi, this is hawkzy’s program"是跟HelloWorldApplication.java里的代码相匹配:

    @GetMapping("/hi")
    public String hi() {
        return "hi, this is hawkzy's program";
    }

具体可以翻看之前的文章JAVA spring boot 微服务快速上手(01)。

6. 还要注意在pom.xml里是否引入了测试依赖:

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-testartifactId>
    <scope>testscope>
dependency>

7. 执行结果:

JAVA spring boot 微服务快速上手(02)_第2张图片

你可能感兴趣的:(微服务,spring,boot)