Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

2.42. SpringBootTest

2.42.1. Maven 依賴

		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>		
		
		

2.42.2. 測試類

創建測試類,在測試類的類頭部添加:@RunWith(SpringRunner.class)和@SpringBootTest註解,在測試方法的前添加@Test,最後選擇方法右鍵run運行。

		
@RunWith(SpringRunner.class)
@SpringBootTest
public class WalletTest {

	@Autowired
	WalletService walletService;

	public WalletTest() {
		// TODO Auto-generated constructor stub
	}

	@Test
	public void test() throws Exception {

		Assert.assertEquals(5,5);

	}
}
		
		

2.42.2.1. Junit基本註解介紹

			
@RunWith
在JUnit中有很多個Runner,他們負責調用你的測試代碼,每一個Runner都有各自的特殊功能,你要根據需要選擇不同的Runner來運行你的測試代碼。
如果我們只是簡單的做普通Java測試,不涉及Spring Web項目,你可以省略@RunWith註解,這樣系統會自動使用預設Runner來運行你的代碼。					
			
//在所有測試方法前執行一次,一般在其中寫上整體初始化的代碼 
@BeforeClass

//在所有測試方法後執行一次,一般在其中寫上銷毀和釋放資源的代碼 
@AfterClass

//在每個測試方法前執行,一般用來初始化方法(比如我們在測試別的方法時,類中與其他測試方法共享的值已經被改變,為了保證測試結果的有效性,我們會在@Before註解的方法中重置數據)
@Before

//在每個測試方法後執行,在方法執行完成後要做的事情
@After

// 測試方法執行超過1000毫秒後算超時,測試將失敗 
@Test(timeout = 1000)

// 測試方法期望得到的異常類,如果方法執行沒有拋出指定的異常,則測試失敗
@Test(expected = Exception.class)

// 執行測試時將忽略掉此方法,如果用於修飾類,則忽略整個類 
@Ignore("not ready yet") 
@Test	
			
			

2.42.3. 

2.42.3.1. Assert.assertEquals 判斷相等

2.42.3.2. Assert.assertTrue

2.42.4. JPA 測試

		
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MessageRepository messageRepository;

    @Test
    public void test() throws Exception {

        userRepository.save(new User("Neo", 10));
        userRepository.save(new User("Jam", 20));
        userRepository.save(new User("Tom", 30));
        userRepository.save(new User("Sam", 40));
        userRepository.save(new User("Leo", 50));

        Assert.assertEquals(5, userRepository.findAll().size());

        messageRepository.save(new Message("Neo", "How are you?"));
        messageRepository.save(new Message("Jam", "Hi!"));
        messageRepository.save(new Message("Sam", "What's going on?"));

        Assert.assertEquals(3, messageRepository.findAll().size());

    }
}		
		
		

2.42.5. 

		
package cn.netkiller.rest;
 
import java.net.URI;
import java.net.URISyntaxException;
 
import org.junit.Assert;
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.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
 
import cn.netkiller.rest.model.Employee;
 
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class SpringBootDemoApplicationTests
{
    @Autowired
    private TestRestTemplate restTemplate;
     
    @LocalServerPort
    int randomServerPort;
 
    @Test
    public void testAddEmployeeSuccess() throws URISyntaxException
    {
        final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
        URI uri = new URI(baseUrl);
        Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
         
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-COM-PERSIST", "true");     
 
        HttpEntity<Employee> request = new HttpEntity<>(employee, headers);
         
        ResponseEntity<String> result = this.restTemplate.postForEntity(uri, request, String.class);
         
        //Verify request succeed
        Assert.assertEquals(201, result.getStatusCodeValue());
    }
     
    @Test
    public void testAddEmployeeMissingHeader() throws URISyntaxException
    {
        final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
        URI uri = new URI(baseUrl);
        Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
         
        HttpHeaders headers = new HttpHeaders();
 
        HttpEntity<Employee> request = new HttpEntity<>(employee, headers);
         
        ResponseEntity<String> result = this.restTemplate.postForEntity(uri, request, String.class);
         
        //Verify bad request and missing header
        Assert.assertEquals(400, result.getStatusCodeValue());
        Assert.assertEquals(true, result.getBody().contains("Missing request header"));
    }
 
}	
		
		

2.42.6. Controller單元測試

創建測試類,在測試類的類頭部添加:@RunWith(SpringRunner.class)、@SpringBootTest、@ AutoConfigureMockMvc註解,在測試方法的前添加@Test,最後選擇方法右鍵run運行。

使用@Autowired 注入MockMvc,在方法中使用 mvc測試功能。示例:

		
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StudentControllerTest {
    @Autowired
    private MockMvc mvc;


    @Test
    public void getAll() throws Exception {

              mvc.perform(MockMvcRequestBuilders.get("/student/getAll")).andExpect(MockMvcResultMatchers.model().attributeExists("students"));

    }


     @Test
     public void save() throws Exception {

               Student student = new Student();
               student.setAge(12);
               student.setId("1003");
               student.setName("Neo");
               mvc.perform(MockMvcRequestBuilders.post("/student/save", student));

     }

 

     @Test
     public void delete() throws Exception {

               mvc.perform(MockMvcRequestBuilders.delete("/student/delete?id=1002"));

     }

    

     @Test
     public void index() throws Exception {

               mvc.perform(MockMvcRequestBuilders.get("/student/index")).andReturn();

     }

}		
		
		

2.42.7. WebTestClient

		
package cn.netkiller.webflux;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;

@RunWith(SpringRunner.class)
@SpringBootTest
public class WebfluxApplicationTests {

	@Test
	public void contextLoads() {
	}

	private WebTestClient webTestClient;

	@Before
	public void setUp() {
		this.webTestClient = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build();
	}

	@Test
	public void sample() throws Exception {
		this.webTestClient.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello world!");
	}

	@Test
	public void client() {

	}
}