Rah*_*tik 7 grails unit-testing traits spock grails-2.4
我正在使用Traits来制作我的控制器DRY.我想使用Spock对Trait类进行单元测试.这是我的样本特征和Spock测试用例:
trait SomeTrait {
public void checkSomething (Closure c ){
// Do some operation
c.call
}
}
@TestMixin(GrailsUnitTestMixin)
class SomeTraitSpec extends Specification {
void "test checkSomething "(){
setup:
MockedClass mockedObj = new MockedClass()
def x=0
def c = {
x=1
}
when:
mockedObj.checkSomething(c)
then:
assert x==1
}
}
class MockedClass implements PermissionTrait {
// some thing
}
Run Code Online (Sandbox Code Playgroud)
由于trait是一个接口,我在我的测试用例中有一个Mocked类正在实现Trait,我创建了一个这个Mocked类的对象并调用我要测试的Trait方法.这是正确的方法,如果不是,请用恰当的例子指出正确的方向.
小智 8
Groovy的类型强制可用于在运行时将特性从特征添加到类.
class MyTraitSpec extends Specification
{
@Shared
MyTrait testInstance = new Object() as MyTrait
// ...
}
Run Code Online (Sandbox Code Playgroud)
您应该知道这会创建一个代理实例,尽管文档(http://docs.groovy-lang.org/docs/groovy-2.3.0/html/documentation/core-traits.html#_runtime_implementation_of_traits)表示代理保证实现trait和any/all接口,如果你检查对象的具体类型,这可能会导致问题.
| 归档时间: |
|
| 查看次数: |
1645 次 |
| 最近记录: |