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

  • 相关阅读:
    DHTML【11】--DOM
    sql 查询强制使用HASH连接性能测试比较
    Winform开发框架之读卡器和条码扫描枪的数据接收处理
    DevExpress的XtraReport和微软RDLC报表的使用和对比
    sql server日期时间转字符串
    C#在线更新程序[下载程序、解压缩程序、控制台程序]
    C# 定时器事件(设置时间间隔,间歇性执行某一函数,控制台程序)
    用C#用C#实现窗体在规定时间弹出,例如:10:00.弹出后关闭。并在5分钟后再次弹出。5次后停止。最好有具体代码实现窗体在规定时间弹出,例如:10:00.弹出后关闭。并在5分钟后再次弹出。5次后停止。最好有具体代码
    C#多线程学习之(五)使用定时器进行多线程的自动管理
    C# 文件与目录的基本操作(System.IO)
  • 原文地址:https://www.cnblogs.com/lspz/p/6727123.html
Copyright © 2011-2022 走看看