SpringBoot 單元測試

一、環境搭建

集成開發環境:Intelij IDEA

  1.添加maven依賴:

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

2.設置自動生成測試代碼目錄地址(非必要操作

 

 

3.如果項目沒有自動生成test目錄,需要自己新建目錄,並在IDEA中標記test目錄

  4.爲了避免對每個controller、service都添加重複的註解,可以創建測試基類(非必要操作


import javax.servlet.http.Cookie;

import org.junit.After;
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.mock.web.MockHttpSession;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:application-dev.properties")
public class BaseTestCase {

    @Autowired
    private WebApplicationContext wac;

    public MockMvc mvc;
    public MockHttpSession session;
    public Cookie[] cookies = new Cookie[1];

    @Before
    public void before() throws Exception {
        mvc = MockMvcBuilders.webAppContextSetup(wac).build();
        session = new MockHttpSession();
        cookies[0] = new Cookie("mykey","myvalue");
    }

    @After
    public void after() throws Exception {
    }

    @Test
    public void testLoad() {
    }

    public void testGetIsOK(String url) throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(url).session(session).cookie(cookies))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }
}

其中my.properties爲自定義的properties文件,如果是springboot默認創建的application.properties,則不用添加該註解

5.創建test類進行測試,環境搭建完畢

二、Service測試

1.數值相等

    @Test
    public void testgetMessage() throws Exception {
        Object obj = Object Service.getMessage(68);
        assertThat(obj , notNullValue());
        assertThat(obj .getId(), equalTo(68));
    }

 2.數值比較

    @Test
    public void testadd() throws Exception {
        int result = ObjService.add(a);
        assertThat(result, greaterThan(1));
    }

三、Controller測試

1.get測試

    @Test
    public void testGet() throws Exception {
        mvc.perform(
            MockMvcRequestBuilders.get(baseUrl + "/get/1")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
        ).andExpect(MockMvcResultMatchers.status().isOk());
    }

 2.post測試

    @Test
    @Transactional
    public void testDelete() throws Exception {
        Map<String,Object> content = new HashMap<>();
        content.put("uid",uid);
        content.put("id",1);
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        String requestJson = ow.writeValueAsString(content);
        mvc.perform(MockMvcRequestBuilders.post(baseUrl + "/delete")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestJson)
        ).andExpect(MockMvcResultMatchers.status().isOk());
    }

備註:@Transactional 爲回滾測試,如在數據庫中新增數據後回滾,防止添加髒數據

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章