zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    poj 1262 地板覆盖问题
    混合图 (Standard IO)
    matrix
    麻将 (Standard IO)
    C#多线程编程之:异步事件调用
    使用线程池与专用线程
    C#多线程编程之:Timer(定时器)使用示例
    C#多线程编程之:异步方法调用
    WCF 快速入门
    c#实现每隔一段时间执行代码(多线程)
  • 原文地址:https://www.cnblogs.com/lspz/p/6727123.html
Copyright © 2011-2022 走看看