zoukankan      html  css  js  c++  java
  • Spock高质量单元测试实操篇

    spock的介绍

    <img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmipihftrbj30xc0gi764.jpg" style="zoom:25%;" />

    spock与junit等单元测试框架一样都是java生态内比较流行的单元测试框架,不同点在于spock基于groovy动态语言,这使得spock相较于传统Java单元测试框架具备了更强的动态能力,从语法风格来比较 spock 单元测试的语义性更强,代码本身更能简洁直观的体现出测试用例。下对spock与传统java单元测试进行对比。

    传统的java单元测试

        @Test
        public void testVersionFilter() {
            PowerMockito.mockStatic(CurrentScope.class, CommonWebScope.class);
            PowerMockito.when(CurrentScope.appVer()).thenReturn(AppVer.of("4.0.0"));
            PowerMockito.when(CurrentScope.clientId()).thenReturn(ClientId.ANDROID);
            PowerMockito.when(CommonWebScope.appType()).thenReturn(AppType.ANDROID_CN );
    
            TestResource resource;
            // 在android ios 最小版本之上
            resource = TestResource.builder()
                    .androidMinVersion("3.0.0")
                    .androidMaxVersion("6.0.0")
                    .iosMinVersion("4.0.0")
                    .iosMaxVersion("4.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(true);
    
            // 在android ios 最小版本之上 android 在最大版本上
            resource = TestResource.builder()
                    .androidMinVersion("3.0.0")
                    .androidMaxVersion("4.0.0")
                    .iosMinVersion("4.0.0")
                    .iosMaxVersion("4.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(false);
    
            // 在android 最小版本之下 ios之上
            resource = TestResource.builder()
                    .androidMinVersion("7.0.0")
                    .iosMinVersion("3.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(false);
    
            PowerMockito.when(CurrentScope.appVer()).thenReturn(AppVer.of("5.0.0"));
            PowerMockito.when(CurrentScope.clientId()).thenReturn(ClientId.IPHONE);
            PowerMockito.when(CommonWebScope.appType()).thenReturn(AppType.IOS_KWAI);
    
            // 在android ios 最小版本之上
            resource = TestResource.builder()
                    .androidMinVersion("3.0.0")
                    .iosMinVersion("4.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(true);
    
            resource = TestResource.builder()
                    .androidMinVersion("4.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(true);
    
            resource = TestResource.builder()
                    .androidMinVersion("3.0.0")
                    .iosMinVersion("4.0.0")
                    .iosMaxVersion("6.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(true);
    
            resource = TestResource.builder()
                    .androidMinVersion("3.0.0")
                    .iosMinVersion("4.0.0")
                    .iosMaxVersion("4.5.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(false);
    
            // 在android 最小版本之上 ios之下
            resource = TestResource.builder()
                    .androidMinVersion("3.0.0")
                    .iosMinVersion("7.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(false);
    
            // 在android 最小版本之下 ios之上
            resource = TestResource.builder()
                    .androidMinVersion("7.0.0")
                    .iosMinVersion("3.0.0")
                    .build();
            Assertions.assertThat(resource.isValid()).isEqualTo(true);
        }
    

    错误结果的报告

    org.opentest4j.AssertionFailedError: 
    Expecting:
     <true>
    to be equal to:
     <false>
    but was not.
    Expected :false
    Actual   :true
    <Click to see difference>
    

    基于groovy的spock重写

        def "测试通用版本过滤"() {
            setup:
            PowerMockito.mockStatic(CurrentScope.class, CommonWebScope.class);
            PowerMockito.when(CurrentScope.appVer()).thenReturn(AppVer.of(appVer));
            PowerMockito.when(CurrentScope.clientId()).thenReturn(clientId);
            PowerMockito.when(CommonWebScope.appType()).thenReturn(appType);
    
            when:
            def valid = new TestResource(
                    androidMinVersion: androidMinVersion,
                    androidMaxVersion: androidMaxVersion,
                    iosMinVersion: iosMinVersion,
                    iosMaxVersion: iosMaxVersion
            ).isValid()
    
            then:
            valid == checkResult
    
            where:
            appVer  | clientId         | appType            | androidMinVersion | androidMaxVersion | iosMinVersion | iosMaxVersion || checkResult
            "4.0.0" | ClientId.ANDROID | AppType.ANDROID_CN | "3.0.0"           | "6.0.0"           | "4.0.0"       | "4.0.0"       || true
            "4.0.0" | ClientId.ANDROID | AppType.ANDROID_CN | "3.0.0"           | "4.0.0"           | "4.0.0"       | "4.0.0"       || false
            "4.0.0" | ClientId.ANDROID | AppType.ANDROID_CN | "7.0.0"           | null              | "3.0.0"       | null          || false
    
            "5.0.0" | ClientId.IPHONE  | AppType.IOS        | "3.0.0"           | null              | "4.0.0"       | null          || true
            "5.0.0" | ClientId.IPHONE  | AppType.IOS        | "4.0.0"           | null              | null          | null          || true
            "5.0.0" | ClientId.IPHONE  | AppType.IOS        | "3.0.0"           | null              | "4.0.0"       | "6.0.0"       || true
            "5.0.0" | ClientId.IPHONE  | AppType.IOS        | "3.0.0"           | null              | "4.0.0"       | "4.5.0"       || false
            "5.0.0" | ClientId.IPHONE  | AppType.IOS        | "3.0.0"           | null              | "7.0.0"       | null          || false
            "5.0.0" | ClientId.IPHONE  | AppType.IOS        | "7.0.0"           | null              | "3.0.0"       | null          || true
        }
    

    错误结果的报告

    Condition not satisfied:
    
    resource.isValid() == checkResult
    |        |         |  |
    |        true      |  false
    |                  false
    com.demo.play.model.activity.TestResource@1c58d7be
    
    <Click to see difference>
    
    
        at com.demo.play.model.activity.AdminResourceSpockTest.测试通用版本过滤(AdminResourceSpockTest.groovy:44)
    

    通过以上传统java单元测试与spock单元测试的比对可以感受到,spock单元测试更为简短精炼,语义化更强,在异常用例报告上,spock也更清晰明了。

    引入

    目前spock主流两个版本 1.x 及 2.x ,当前 2.x 无法与 PowerMock 协同使用,若有大量静态方法需要 Mock 请使用 spock 1.x 版本

    spock 2.x 版本

    由于2.x基于junit5,不再兼容powerMock,目前无太好的静态方法mock。但是groovy升级到3.0,在闭包等方式上更简练了。

            <!-- spock 2.0 并会自动引入groovy3.0 -->
            <dependency>
                <groupId>org.spockframework</groupId>
                <artifactId>spock-spring</artifactId>
                <version>2.0-M2-groovy-3.0</version>
                <scope>test</scope>
            </dependency>
    

    spock 1.x 版本(推荐)

    spock 1.x 版本可以与 powerMock配合使用,可以满足基本所有单元测试场景,但不支持 groovy3 tab 闭包

            <!-- spock -->
            <dependency>
                <groupId>org.codehaus.groovy</groupId>
                <artifactId>groovy-all</artifactId>
                <version>2.4.15</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.spockframework</groupId>
                <artifactId>spock-spring</artifactId>
                <version>1.2-groovy-2.4</version>
                <scope>test</scope>
            </dependency>
    

    这样我们可以开始编写spock单元测试了,在 /src/test/(java|groovy)/ 对应的测试包下新建Groovy单元测试类,下是一个最简单的spock测试实例

    // 继承 spock.lang.Specification
    class FileRestTest extends Specification {
        // 这是一个简单的单元测试方法
        // 这里方法定义方式称为契约,可以直接用中文
        def "单元测试方法"() {
            expect:
            Math.max(1, 2) == 3
        }
    }
    

    Blocks

    k2fnQ.png
        def "测试 fileKey 与 host 的映射"() {
            given:
            def hostMap = ["play-dev.local.cn": "play-admin-dev"]
            def fileRest = new FileRest()
    
            when:
            def resultKey = fileRest.parseFileKeyByHostMap(uri, host, hostMap)
    
            then:
            resultKey == checkKey
    
            where:
            uri                             |host                           |checkKey
            "/look-admin/index.html"      |"look.test.demo.com"      |null
            "/banner/index.html"            |"play-dev.local.cn"            |"play-admin-dev/banner/index.html"
            "/banner/"                      |"play-dev.local.cn"            |"play-admin-dev/banner/index.html"
            "/banner"                       |"play-dev.local.cn"            |"play-admin-dev/banner/index.html"
        }
    

    上源码展示了一个完整的spock单元测试方法,与java最大的不同spock的单元测试可以拥有given、when、then等块对单元测试逻辑进行分隔。

    分块替换功能说明
    given setup 初始化函数、MOCK 非必要
    when expect 执行待测试的函数 when 和 then 必须成对出现
    then expect 验证函数结果 when 和 then 可以被 expect 替换
    where   多套测试数据的检测 spock的特性功能
    and   对其余块进行分隔说明 非必要

    用expect替换 when & then

    def "测试 fileKey 与 host 的映射"() {
        given:
        def hostMap = ["play-dev.local.cn": "play-admin-dev"]
        def fileRest = new FileRest()
    
        expect:
        def resultKey = fileRest.parseFileKeyByHostMap(uri, host, hostMap)
        // 在spock expect、then块中不需要显示的断言语句
        // 当一个表达式返回为boolean时其自动作为断言存在
        resultKey == checkKey
    
        where:
        ...
    }
    

    where

    where主要作用用于提供多组测试数据,其可以以数据表或者列表的形式来为参数进行多次赋值。

    // 数据表:
    def "测试最大数"() {
        expect:
        Math.max(a,b) == result
        
        // 这样一个单元测试会验证两组数据
        // 第一组 a = 1 , b = 2, result = 2
        // 第二组 a = 3 , b = 0, result = 3
        where:
        a   |b  |result
        1   |2  |2
        3   |0  |3
    }
    
    // 数据列表
    def "测试最大数"() {
        expect:
        Math.max(a,b) == result
        
        // 这样一个单元测试会验证两组数据
        // 第一组 a = 1 , b = 2, result = 2
        // 第二组 a = 3 , b = 0, result = 3
        where:
        a << [1,3]
        b << [2,0]
        result << [2,3]
    }
    

    MOCK

    spock的mock功能非常强大,语义性较传统java mock框架更突出。

    mock 对象的构造

        // 通过传入class参数来构建
        def person = Mock(Person)
        def person = Spy(Person)
        def person = Stub(Person)
    
        // 通过声明类型来构建 Spy\Stub同
        Person person = Mock()
    
        // 交互式的创建 Spy\Stub同
        Person person = Mock {
            getName() >> "bob"
        }
        def person = Mock(Person) {
            getName() >> "bob"
        }
    

    简单的返回值mock

        def "演示mock"() {
            given:
            def resource = Mock(Resource)
            // >> 用于Mock返回
            resource.getResourceId() >> 1L
    
            expect:
            resource.getResourceId() == 1L
        }
    
    

    链式mock

        def "演示mock"() {
            given:
            def resource = Mock(Resource)
            // 第一次、二次、三次、三次 分别返回 1、2、3、4
            resource.getResourceId() >>> [1L,2L,3L] >> 4L
    
            expect:
            resource.getResourceId() == 1L
            resource.getResourceId() == 2L
            resource.getResourceId() == 3L
            resource.getResourceId() == 4L
        }
    
        def "演示mock"() {
            given:
            def resource = Mock(Resource)
            // 第一次调用
            1 * resource.getResourceId() >> 1L
            // 第二次到第三次
            2 * resource.getResourceId() >> 2L
            // 第四次到第六次
            3 * resource.getResourceId() >> 3L
    
            expect:
            resource.getResourceId() == 1L
            resource.getResourceId() == 2L
            resource.getResourceId() == 2L
            resource.getResourceId() == 3L
            resource.getResourceId() == 3L
            resource.getResourceId() == 3L
        }
    

    异常mock

        def "演示mock"() {
            given:
            def resource = Mock(Resource)
            resource.getResourceId() >> {throw new IllegalArgumentException()}
    
            when:
            resource.getResourceId()
    
            then:
            thrown(IllegalArgumentException)
        }
    

    复杂逻辑mock

        def "演示mock"() {
            given:
            def person = Mock(Person)
            person.say(_) >> { 
                args -> "hello " + args[0]
            }
    
            when:
            def msg = person.say("world")
    
            then:
            msg == "hello world"
        }
    

    mock & spy & stub

    mock 返回的是一个所有方法都为空值的对象,当我们对一个对象部分方法进行mock,但其余方法希望基于真实对象逻辑时可以采用Spy()。

    spy基于一个真实的对象,只有被Mock的方法会按指定值返回,其余方法行为与真实对象一致。

    stub与mock的区别在于它只有mock的方法返回对应值,未mock的方法会返回无意义的Stub对象本身,另外mock、spy对象能统计调用次数。

        static class Person {
            def getName() {
                "tom"
            }
    
            def getAge() {
                18
            }
        }
    
        def "演示mock"() {
            given:
            def mockPerson = Mock(Person)
            def spyPerson = Spy(Person)
            def stubPerson = Stub(Person)
            mockPerson.getName() >> "bob"
            spyPerson.getName() >> "bob"
            stubPerson.getName() >> "bob"
    
            expect:
            mockPerson.getName() == "bob"
            spyPerson.getName() == "bob"
            stubPerson.getName() == "bob"
            mockPerson.getAge() == null
            spyPerson.getAge() == 18
            stubPerson.getAge() != 18 && stubPerson.getAge() != null
        }
    

    mock static method (2.x 版本无法支持)

    spock 有GroovyMock可以在Groovy代码范围内对静态方法进行mock,但无法进行Java 静态方法的mock。加入powerMock依赖:

            
            <dependency>
                <groupId>net.bytebuddy</groupId>
                <artifactId>byte-buddy</artifactId>
                <version>1.8.21</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.objenesis</groupId>
                <artifactId>objenesis</artifactId>
                <version>2.6</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-api-mockito2</artifactId>
                <version>2.0.0</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-core</artifactId>
                <version>2.0.0</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-module-junit4</artifactId>
                <version>2.0.0</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-module-junit4-rule</artifactId>
                <version>2.0.0</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-classloading-xstream</artifactId>
                <version>2.0.0</version>
                <scope>test</scope>
            </dependency>
    

    使用powerMock mock 静态方法

    @RunWith(PowerMockRunner.class)
    @PowerMockRunnerDelegate(Sputnik.class)
    // 此注解指定要mock的静态方法类
    @PrepareForTest(value = [CurrentScope.class, CommonWebScope.class])
    class AdminResourceSpockTest extends Specification {
        
        def "测试通用版本过滤"() {
            setup:
            // 这里对所有需要mock的静态方法类进行mock
            PowerMockito.mockStatic(CurrentScope.class, CommonWebScope.class);
            // 当调用 CurrentScope.appVer() 时将按thenReturn内的值返回
            PowerMockito.when(CurrentScope.appVer()).thenReturn内的值返回(AppVer.of(appVer));
            PowerMockito.when(CurrentScope.clientId()).thenReturn(clientId);
            PowerMockito.when(CommonWebScope.appType()).thenReturn(appType);
    
            when:
            def valid = new TestResource(
                    androidMinVersion: androidMinVersion,
                    androidMaxVersion: androidMaxVersion,
                    iosMinVersion: iosMinVersion,
                    iosMaxVersion: iosMaxVersion
            ).isValid()
    
            then:
            valid == checkResult;
    
            where:
            ...
        }
    }
    
    

    assert

    spock断言非常简练,在then或者expect区块中,一个简单的boolean语句就可以作为一个断言,无需其他工具或关键词

        then:
        // 简单的boolean表达式
        code == 1
        
        // 调用次数统计 http://spockframework.org/spock/docs/1.3/all_in_one.html#_cardinality
        // mockObj这个mock对象在调用中被调用过一次,参数中 _ 代表可以是任意值匹配
        1 * mockObj.run(_)
        // 参数中指定传递1时被调用过一次
        1 * mockObj.run(1)
        // 被调用过1次及以上,且最多三次
        (1..3) * mockObj.run(_)
        // 至少调用一次
        (1.._) * mockObj.run(_)
        // 任何mock对象中方法名为run的方法被调用一次
        1 * _.run(_)
    

    groovy的一些语言特性

    由于groovy具备很多语法特性,可以使得我们单元测试的编写更简洁清晰

    对象构建

        // 用闭包
        def resource = new Resource().with {
            setResourceId(1L)
            return it
        }
        
        // 用构造传参
        def resource = new Resource(resourceId: 1L)
    

    字符串

    groovy字符串可以通过 ''' 来编写无需转意符的字符,这在我们写一些测试json数据时帮助很大。

        // java
        String json = "{\"name\":\"tom\",\"age\":18}"
        // groovy
        def json = '''{"name": "tom","age": 18}'''
    

    列表

        def resourceList = [
            new Resource(resourceId: 2L),
            new Resource(resourceId: 3L),
            new Resource(resourceId: 1L),
            new Resource(resourceId: 4L)
        ]
    
        // << 可以替代 list.add
        resourceList << new Resource(resourceId: 5L) << new Resource(resourceId: 6L)
    
  • 相关阅读:
    2020杭电多校第二场 1006.The Oculus
    2020杭电多校第一场 1005.Fibonacci Sum
    数论——中国剩余定理
    数论——线性同余方程
    数论——乘法逆元
    数论——裴蜀定理
    javascript预解析和作用域
    数组的排序..........加深难度
    值类型和引用类型
    js中的==和===
  • 原文地址:https://www.cnblogs.com/qq3245792286/p/15438897.html
Copyright © 2011-2022 走看看