简体   繁体   中英

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM