笔记 | Spring Boot 的测试

《深入理解Spring Cloud与微服务构建》笔记 4.2.3:
该测试章节要与前面的小案例结合
该章节代码:

package com.example.demo;


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 static org.junit.Assert.*;
import static org.hamcrest.Matchers.equalTo;

import java.net.MalformedURLException;
import java.net.URL;

@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 MalformedURLException {
     
        this.base = new URL("http://localhost:" + port + "/hi");
    }

    @Test
    public void getHello(){
     
        ResponseEntity<String> response = template.getForEntity(base.toString(),String.class);
        assertThat(response.getBody(),equalTo("hi,I'm forezp"));
    }
}

前面案例代码:
注意:该类本身就有,即填充代码,不需要创建类

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {
     

    public static void main(String[] args) {
     
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping("/hi")
    public String hi(){
     
        return "hi,I'm forezp";
    }

}

实现效果
笔记 | Spring Boot 的测试_第1张图片
修改成一样的句子则测试成功
笔记 | Spring Boot 的测试_第2张图片
如果出现空指针错误,注意看代码是否打错了

你可能感兴趣的:(Spring,Cloud,JAVA)