• SpringBoot 2.x (4):配置文件与单元测试


    SpringBoot的配置文件有默认的application.properties

    还可以使用YAML

    区别:

    application.properties示例:
    server.port=8090
    server.session-timeout=30
    server.tomcat.max-threads=0
    server.tomcat.uri-encoding=UTF-8

    application.yml示例:
    server:
       port: 8090  
       session-timeout: 30
       tomcat.max-threads: 0
       tomcat.uri-encoding: UTF-8

    两种方式都优于SSM的XML配置形式,个人更偏向于使用properties文件

    SpringBoot默认的配置项:

    这里不多写了,可以去Spring官网查找

    也可以参考一位大佬的博客:

    https://www.cnblogs.com/SimpleWu/p/10025314.html

    如何在代码中读取配置文件中的自定义信息呢?

    比如:

    file.path=D:\temp\images\

    想要在代码中获取这个值的话:

        @Value("${file.path}")
        private String FILE_PATH;

    将配置文件映射到实体类:

    第一种方式:手动给实体类属性注入

    配置文件:

    test.name=springboot
    test.domain=www.dreamtech.org

    实体类:

    package org.dreamtech.springboot.domain;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ServerSettings {
        @Value("${test.name}")
        private String name;
        @Value("${test.domain}")
        private String domain;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDomain() {
            return domain;
        }
    
        public void setDomain(String domain) {
            this.domain = domain;
        }
    
    }

    Controller:

        @Autowired
        private ServerSettings serverSettings;
        
        @RequestMapping("/test")
        @ResponseBody
        private ServerSettings test() {
            return serverSettings;
        }

    第二种方式:根据前缀自动注入

    实体类:

    package org.dreamtech.springboot.domain;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = "test")
    public class ServerSettings {
        private String name;
        private String domain;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDomain() {
            return domain;
        }
    
        public void setDomain(String domain) {
            this.domain = domain;
        }
    
    }

    注意:如果使用了前缀的方式,那么不能再使用@Value注解了!

    下面进行SpringBoot测试学习:

    普通的单元测试:

    首先导入依赖:通常SpringBoot新项目带有这个依赖,如果没有,自行导入即可

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

    在test目录下新建测试类:

    @Test用于测试;@Before测试前运行;@After测试后运行

    package org.dreamtech.springboot;
    
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import junit.framework.TestCase;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { SpringbootApplication.class })
    public class SpringBootTestDemo {
        @Test
        public void testOne() {
            System.out.println("hello world!");
            TestCase.assertEquals(1, 1);
        }
    
        @Before
        public void testBefore() {
            System.out.println("Before");
        }
    
        @After
        public void testAfter() {
            System.out.println("After");
        }
    }

    对API接口进行测试:使用MockMVC

    MockMVC相当于就是一个HTTP客户端,模拟用户使用浏览器进行操作

    写一个接口进行测试:

        @RequestMapping("/test")
        @ResponseBody
        private String test() {
            return "test";
        }

    测试类:

    package org.dreamtech.springboot;
    
    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.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;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    
    import junit.framework.TestCase;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = { SpringbootApplication.class })
    @AutoConfigureMockMvc
    public class MockMvcTest {
        @Autowired
        private MockMvc mockMvc;
    
        @Test
        public void apiTest() throws Exception {
            // 以GET方式访问/test路径,如果返回是200状态码说明调用成功
            MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test"))
                    .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
            TestCase.assertEquals(mvcResult.getResponse().getStatus(), 200);
        }
    }

    最后记录一点有趣的东西:

    启动的时候显示SpringBoot多单调啊,不如找一些好看的!

    在classpath下面写一个banner.txt:

    ////////////////////////////////////////////////////////////////////
    //                          _ooOoo_                               //
    //                         o8888888o                              //
    //                         88" . "88                              //
    //                         (| ^_^ |)                              //
    //                         O  =  /O                              //
    //                      ____/`---'\____                           //
    //                    .'  \|     |//  `.                         //
    //                   /  \|||  :  |||//                          //
    //                  /  _||||| -:- |||||-                         //
    //                  |   | \  -  /// |   |                       //
    //                  | \_|  ''---/''  |   |                       //
    //                    .-\__  `-`  ___/-. /                       //
    //                ___`. .'  /--.--  `. . ___                     //
    //              ."" '<  `.___\_<|>_/___.'  >'"".                  //
    //            | | :  `- \`.;` _ /`;.`/ - ` : | |                 //
    //               `-.   \_ __ /__ _/   .-` /  /                 //
    //      ========`-.____`-.___\_____/___.-`____.-'========         //
    //                           `=---='                              //
    //      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
    //            佛祖保佑       永不宕机     永无BUG                  //
    ////////////////////////////////////////////////////////////////////
    Spring Boot Version: ${spring-boot.version}
  • 相关阅读:
    webpack中设置jquery为全局对象
    JS判断不同web访问环境,主要针对移动设备,
    js比较两个日期天数差
    原生js跨域
    我们项目中用到的jsonp跨域
    Js跨域解决方法总结
    js call的使用,js call 方法实现继承
    windows下配置bower路径
    兼容弹层代码
    自定义下拉列表框(2015.1.30)
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/10808092.html
Copyright © 2020-2023  润新知