Testing guide

文档

http://www.groovy-lang.org/testing.html


1、Language Features

除了对JUnit的集成支持之外,Groovy编程语言还具有已被证明对测试驱动开发非常有价值的功能。

1.1 断言

2、Mocking and Stubbing

2.1 MockFor and StubFor

class Person {
    String first, last
}

class Family {
    Person father, mother
    def nameOfMother() { "$mother.first $mother.last" }
}


def mock = new MockFor(Person)      
mock.demand.getFirst{ 'dummy' }
mock.demand.getLast{ 'name' }
mock.use {                          
    def mary = new Person(first:'Mary', last:'Smith')
    def f = new Family(mother:mary)
    assert f.nameOfMother() == 'dummy name'
}
mock.expect.verify()    

class Person {
    String first, last
}

class Family {
    Person father, mother
    def nameOfMother() { "$mother.first $mother.last" }
}

def stub = new StubFor(Person)      
stub.demand.with {                  
    getLast{ 'name' }
    getFirst{ 'dummy' }
}
stub.use {                          
    def john = new Person(first:'John', last:'Smith')
    def f = new Family(father:john)
    assert f.father.first == 'dummy'
    assert f.father.last == 'name'
}
stub.expect.verify()    

MockForStubFor 不能测试静态编译的类,例如 Java classes 或 使用 @CompileStatic 注解的Groovy classes。
要 stub and/or mock 这些类,你可以使用 Spock 或 Java mocking 库

2.2 EMC(Expando Meta-Class)

Groovy包含一个特殊的 MetaClass,即所谓的 ExpandoMetaClass(EMC)
它允许使用简洁的Closure语法动态添加方法,构造函数,属性和静态方法。

String.metaClass.swapCase = {->
    def sb = new StringBuffer()
    delegate.each {
        sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) :
            Character.toUpperCase(it as char))
    }
    sb.toString()
}

def s = "heLLo, worLD!"
assert s.swapCase() == 'HEllO, WORld!'

class Book {
    String title
}

Book.metaClass.static.create << { String title -> new Book(title:title) }

def b = Book.create("The Stand")
assert b.title == 'The Stand'

// 甚至可以是 构造函数
Book.metaClass.constructor << { String title -> new Book(title:title) }

def b = new Book("The Stand")
assert b.title == 'The Stand'

3、GDK方法

3.1 Iterable#combinations

void testCombinations() {
    def combinations = [[2, 3],[4, 5, 6]].combinations()
    assert combinations == [[2, 4], [3, 4], [2, 5], [3, 5], [2, 6], [3, 6]]
}

3.2 Iterable#eachCombination

void testEachCombination() {
    [[2, 3],[4, 5, 6]].eachCombination { println it[0] + it[1] }
}

4、工具支持

4.1 Test Code Coverage

...

你可能感兴趣的:(Testing guide)