Grails Gmock partial mock example

 
class Foo {
 
    def methodFoo(String param){
        return "methodFoo"
    }
}
 
...
 
class Bar {
 
    def foo
 
    def methodBar(String param){
        return foo.methodFoo(param) + methodBarSecond(param);
    }
 
    def methodBarSecond(String param){
         return "methodBarSecond"
    }
}
 
...
 
import static org.hamcrest.Matchers.any
 
@WithGmock
class BarTests {
 
    @Test
    public void checkMethodBar(){
        def result = "my other result"
        def mockFoo = mock(Foo)
        mockFoo.testMethod(any(String)).returns(result)
 
        Bar bar = new Bar()
        bar.foo = mockFoo
        mock(bar).methodBarSecond(any(String)).returns(result)
 
        play {
            assertEquals (result * 2, bar.methodBar())
        }
    }
}
 

Grails bean factory + method with parameters

 
class MyObjectFactory {
    static final int TYPE_ONE = 1
    static final int TYPE_TWO = 2
 
    def produce(int type){
         if (type == TYPE_ONE){
              return ... // type one
         }
 
         if (type == TYPE_TWO){
              return ... // type two
         }
 
         throw new IllegalArgumentException()
    }
} 
 
...
 
beans {
 
    myObjectFactoryBean(MyObjectFactory)
 
    myObjectBean(myObjectFactoryBean:'produce'){bean->
         bean.constructorArgs = [MyObjectFactory.TYPE_ONE ]
    }
}
 

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.