spring boot 測試和部署

測試

  • 自動生成的Test類中,@RunWith(SpringRunner.class) 開啓Spring集成測試。@SpringBootTest 自動搜索應用啓動類,加載應用的上下文。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReadinglistApplicationTests
  • 針對 Controller測試,可以忽略RequestMapping等標籤,直接測試方法本身,但是無法處理post請求,也無法測試表單和參數的綁定。spring boot有兩種方法可以模擬http請求測試:
    1. spring mock mvc:在模擬servlet容器裏測試控制器。啓動快。
    2. web繼承測試:在嵌入式servlet容器中啓動應用測試。接近真實環境。

模擬spring mvc

  • 獲取web應用上下文,並注入模擬的mvc。
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
  • 編排測試邏輯。需要使用模擬請求測試和校驗類MockMvcRequestBuilders,MockMvcResultMatchers,Matchers。
 package com.example.readinglist;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ReadinglistApplicationTests {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @Before
    public void setupMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testBook() throws Exception {
        Book book = getBook();
        String read1Url = "/readingList/reader1";

        //查詢圖書,結果爲空
        mockMvc.perform(get(read1Url))
                .andExpect(status().isOk())
                .andExpect(view().name("readingList"))
                .andExpect(model().attributeExists("books"))
                .andExpect(model().attribute("books", is(empty())));
        //添加圖書
        mockMvc.perform(post(read1Url)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("title", book.getTitle())
                .param("author", book.getAuthor())
                .param("isbn", book.getIsbn())
                .param("description", book.getDescription()))
                .andExpect(status().is3xxRedirection())
                .andExpect(header().string("Location", read1Url));
        //查詢圖書,結果爲新加的圖書
        mockMvc.perform(get(read1Url))
                .andExpect(status().isOk())
                .andExpect(view().name("readingList"))
                .andExpect(model().attributeExists("books"))
                .andExpect(model().attribute("books", hasSize(1)))
                .andExpect(model().attribute("books", contains(samePropertyValuesAs(book))));
    }

    private Book getBook() {
        Book book = new Book();
        book.setReader("reader1");
        book.setId(1L);
        book.setTitle("title1");
        book.setAuthor("author1");
        book.setIsbn("12345");
        book.setDescription("desc");
        return book;
    }
}

服務器測試

  • springboot1.5之前可以使用WebIntegrationTest註解,啓動嵌入式的servlet容器。參考
  • 同時可以使用Selenium框架進行頁面測試。
  • spring1.5之後暫未找到替代方案。

部署

  • 部署可以直接jar包部署,也可以使用內置的tomcat和外部的tomcat。參考

jar部署

  • nohup + & 後臺運行任務。
nohup java -jar house.jar &
exit

內置tomcat

  • 在application.yml中微調默認配置,如:
server:
  port: 8080
  servlet:
    context-path: /house
  • 打包成jar之後用命令行運行。

外部tomcat

  • 修改啓動類,繼承SpringBootServletInitializer實現configure方法,相當於之前的web.xml,加載spring上下文。
@SpringBootApplication
@EnableTransactionManagement
public class HouseApplication extends SpringBootServletInitializer {

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

    /**
     * 與在web.xml中配置負責初始化Spring應用上下文的監聽器作用類似
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(HouseApplication.class);
    }
}
  • 由於tomcat有外部容器提供,需要將依賴設爲provided,以防與內置容器衝突。
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
      <!--springboot自帶的tomcat並沒有攜帶tomcat-embed-jasper的依賴。
      使用內置tomcat的時候需要設爲默認的complie-->
      <scope>provided</scope>
    </dependency>
  • 打包爲war之後放入tomcat的webapps啓動。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章