Skip to content

Instantly share code, notes, and snippets.

@melix
Created October 27, 2014 14:23
Show Gist options
  • Save melix/89a269cdbdebfa3d5b88 to your computer and use it in GitHub Desktop.
Save melix/89a269cdbdebfa3d5b88 to your computer and use it in GitHub Desktop.
Piece of cake like pattern in Groovy
import groovy.util.ProxyGenerator
import groovy.transform.CompileStatic
// just for tests, can be replaed by any mocking framework
class Mock {
static <T> T f(Class<T> clazz, Closure cl) {
ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(cl, clazz)
}
}
@CompileStatic
class ServiceA {
String m1() { '1' }
}
@CompileStatic
class ServiceB {
String m2() { '2' }
}
@CompileStatic
trait ServiceComponent {
@Lazy ServiceA serviceA = new ServiceA()
@Lazy ServiceB serviceB = new ServiceB()
}
@CompileStatic
class ServiceConsumer implements ServiceComponent {
void test() { println "${serviceA.m1()} ${serviceB.m2()}" }
}
class ServiceConsumer2 extends ServiceConsumer {
ServiceA serviceA = Mock.f(ServiceA) { 'mocked!' }
}
def sc = new ServiceConsumer()
def sc2 = new ServiceConsumer2()
[sc,sc2]*.test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment