Tuesday, November 6, 2012

Using ExpandoMetaClass in unit tests

There is great power in the ExpandoMetaClass, particularly when doing unit tests.
I want to unit test a specific Domain but it uses a service (in this case springSecurityService.encodePassword()) in one of its methods (protected void encodePassword). Rather than have an integration test or mock out the whole service I can just override a method on the fly. This allows me to just test the logic I am interested in.

The code in my test looks like this.


    void setUp() {
        println "setUp()"
        User.metaClass.encodePassword = {->
            password
        }
       
        def user = new User(username: 'user', enabled: true, password: '123').save(flush: true)
        assert user
    }
What I have done is overridden the method encodePassword on the class User.

No comments:

Post a Comment