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 test = this.restTemplate.getForEntity(
                this.base.toString() + "/task", String.class, "test");
        System.out.println(test.getBody());
    }
}

你可能感兴趣的:(Spring boot 1.4.2 单元测试配置)