关于java:Leetcode刷题之spock单元测试

29次阅读

共计 1260 个字符,预计需要花费 4 分钟才能阅读完成。

起因

刷题的时候,写完了代码,总是须要有单元测试验证本人的代码对不对。以前的我比拟蠢,切实 main 办法外面测试我写的逻辑对不对的。这种写法,耗时不说,一个类外面只能有一个 main 办法,导致我写另外一题时,就把上一题的单元测试数据丢了,这样很不好。所以举荐下大家用 spock 做单元测试。

spock 的 pom 文件导入

        <!-- Spock 依赖 -->
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.1-groovy-2.4</version>
            <scope>test</scope>
        </dependency>

        <!-- Spock 须要的 groovy 依赖 -->
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.15</version>
        </dependency>

单元测试流程


在 test 目录上面,创立 groovy 文件,我创立了一个 SolutionTest

此类须要继承 spock 的基类 Specification,能力有后续的解决性能

全局创立要测试的对象,用 def 创立测试方法,在外面写测试逻辑即可

运行后会输入测试用例的运行后果

spock 语法介绍


一个 spock 办法由四局部组成

  1. 变量字段:全局定义下测试方法外面须要频繁用到的对象,属性
  2. 测试模板办法:测试方法运行前和运行后执行的办法
    def setupSpec() {}    // runs once -  before the first feature method
    def setup() {}        // runs before every feature method
    def cleanup() {}      // runs after every feature method
    def cleanupSpec() {}  // runs once -  after the last feature method
  1. 测试方法:咱们要测试的代码的主体
  2. 测试帮忙办法:没怎么用过

测试方法书写

def "test count"() {
        given:  // 前置参数
        when:   // 执行须要测试的代码
        then:   // 验证执行后果
        where:  // 参数赋予不同值
    }

测试方法次要有四局部组成,性能如备注所示

    def "test count1"() {
        given:
        Solution solution = new Solution()
        when:   // 执行须要测试的代码
        int a = solution.count1(n)
        then:   // 验证执行后果
        a == b
        where:  // n 和 b 的赋值
        n | b
        1 | 1
        2 | 1
    }

下面为举例模板,我在 given 外面定义我要测试的对象,在 when 外面,调用了对象外面的计算方法。then 外面增加了判断语句,a 是后果,b 是我预期的后果,两个须要相等那办法的逻辑就没有问题。where 外面我给 n 和 b 赋值,相当于提供了测试用例。

能够看到执行了两组测试,很是不便。

正文完
 0