Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a spock unit test case for traits in grails 2.4?

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 .

like image 425
Rahul Pratik Avatar asked Jan 06 '15 07:01

Rahul Pratik


1 Answers

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.

like image 161
Poundex Avatar answered Oct 24 '22 13:10

Poundex