Spring Boot 1.4 單元測試


在1.3中單元測試這樣子的類似代碼:

// SpringJUnit支持,由此引入Spring-Test框架支持!
@RunWith(SpringJUnit4ClassRunner.class)
// 指定我們SpringBoot工程的Application啟動類
@SpringApplicationConfiguration(classes = App.class)
//由於是Web項目,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration。
@WebAppConfiguration
public class HelloServiceTest {
}

在1.4中SpringApplicationConfiguration標記為過時了,所以官方就不建議這么使用了,那么在1.4中單元測試怎么使用呢?類似代碼如下:

一、建立一個整合了mybatis的工程

詳見:http://www.cnblogs.com/lspz/p/6723603.html

二、編寫測試類

測試類的文件結構,保持src/test/Java和src/main/java結構一直,即:包+文件夾。

如:com.example包service中類的測試,那么在src/test/java也是建立com.example包,再在包下建立文件夾service.

1、服務類的

package com.example.mapper;

import com.example.dto.User;
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.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUserMapper {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testGetById() {
        User user = userMapper.getById(1L);
        Assert.assertTrue("數據集不對", user.getAge() == 18);
        Assert.assertTrue("數據一致", user.getName().equals("張三"));
    }
}

2.controller類的

package com.example.web;

import com.example.dto.User;
import com.example.mapper.UserMapper;
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.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class TestExample {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testGetById() throws Exception {
        User user = userMapper.getById(1L);
        String uri = "/getUser/1";
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON))
            .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();
        Assert.assertTrue("錯誤,正確的返回值為200", status == 200);
        Assert.assertFalse("數據不一致", !user.toString().equals(content));
    }
}

controller類的第二種寫法

package com.example.web;

import java.net.URL;

import com.example.dto.User;
import com.example.mapper.UserMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

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

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private UserMapper userMapper;

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

    @Test
    public void getHello() throws Exception {
        User user = userMapper.getById(1L);
        ResponseEntity<String> response = template.getForEntity(base.toString(),
            String.class);
        int status = response.getStatusCodeValue();
        String content = response.getBody();
        assertEquals("錯誤,正確的返回值為200", status, 200);
        assertThat(content, equalTo(user.toString()));
    }
}

三、總結

(1)依賴包的引入:pom.xml中僅依賴spring-boot-starter-test,它把相關的依賴全部引入。
(2)@RunWith(SpringRunner.class) 告訴JUnit運行使用Spring的測試支持。SpringRunner是SpringJUnit4ClassRunner的新名字,這個名字只是讓名字看起來簡單些。
(3)@SpringBootTest的意思是“帶有Spring Boot支持的引導程序”(例如,加載應用程序、屬性,為我們提供Spring Boot的所有精華部分)。
(4)通過webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT我們可以讓內置的服務器在隨機端口啟動。
(5)@LocalServerPort注釋注入實際的端口
(6)如果你需要測試JSON 序列化是否如預期般運營,你可以使用 @JsonTest

  • 自動配置Jackson和/或Gson。
  • 添加你可以定義的任一模塊或者 @JsonComonent beans。
  • 觸發任何JacksonTester或GsonTester字段的初始化。

(7)測試您應用程序的JPA插件(Hibernate +Spring數據)可以使用@DataJpaTest注釋。@DataJpaTest將會這樣:

  • 配置一個內存數據庫。
  • 自動配置Hibernate,Spring數據和數據源。
  • 執行@EntityScan。
  • 打開SQL日志記錄。

部分內容參考自:http://www.jointforce.com/jfperiodical/article/1455


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM