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 为回滚测试,如在数据库中新增数据后回滚,防止添加脏数据

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