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

1

8

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 .

Hepplewhite answered 6/1, 2015 at 7:1 Comment(1)
Has anyone faced such a situation ?Hepplewhite
O
11

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.

Olympian answered 8/1, 2015 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.