I am using Traits for making my controllers DRY. I want to unit test the Trait class using Spock. Here is my sample trait and Spock test case respectively:
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
}
Since trait is an interface, I have a Mocked class in my test case which is implementing the Trait, I create an object of this Mocked class and call my Trait method which I want to test. Is this the correct approach, if not please point in the right direction with an apt example .
Groovy's type coercion can be used to add behaviours from a trait to a class at runtime.
class MyTraitSpec extends Specification
{
@Shared
MyTrait testInstance = new Object() as MyTrait
// ...
}
You should be aware that this creates a proxied instance, although the documentation (http://docs.groovy-lang.org/docs/groovy-2.3.0/html/documentation/core-traits.html#_runtime_implementation_of_traits) says the proxy is guaranteed to implement the trait and any/all interfaces, this could cause problems if you're ever checking the concrete type of the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With