1+ package com .baeldung .cglib .proxy ;
2+
3+ import net .sf .cglib .proxy .Enhancer ;
4+ import net .sf .cglib .proxy .FixedValue ;
5+ import net .sf .cglib .proxy .MethodInterceptor ;
6+ import org .junit .Test ;
7+
8+ import static org .junit .Assert .assertEquals ;
9+
10+ public class ProxyTest {
11+ @ Test
12+ public void givenPersonService_whenSayHello_thenReturnResult () {
13+ //given
14+ PersonService personService = new PersonService ();
15+
16+ //when
17+ String res = personService .sayHello ("Tom" );
18+
19+ //then
20+ assertEquals (res , "Hello Tom" );
21+ }
22+
23+ @ Test
24+ public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod () throws Exception {
25+ //given
26+ Enhancer enhancer = new Enhancer ();
27+ enhancer .setSuperclass (PersonService .class );
28+ enhancer .setCallback ((FixedValue ) () -> "Hello Tom!" );
29+ PersonService proxy = (PersonService ) enhancer .create ();
30+
31+ //when
32+ String res = proxy .sayHello (null );
33+
34+ //then
35+ assertEquals ("Hello Tom!" , res );
36+ }
37+
38+ @ Test
39+ public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod () throws Exception {
40+ //given
41+ Enhancer enhancer = new Enhancer ();
42+ enhancer .setSuperclass (PersonService .class );
43+ enhancer .setCallback ((MethodInterceptor ) (obj , method , args , proxy ) -> {
44+ if (method .getDeclaringClass () != Object .class && method .getReturnType () == String .class ) {
45+ return "Hello Tom!" ;
46+ } else {
47+ return proxy .invokeSuper (obj , args );
48+ }
49+ });
50+
51+ //when
52+ PersonService proxy = (PersonService ) enhancer .create ();
53+
54+ //then
55+ assertEquals ("Hello Tom!" , proxy .sayHello (null ));
56+ int lengthOfName = proxy .lengthOfName ("Mary" );
57+ assertEquals (4 , lengthOfName );
58+ }
59+
60+ }
0 commit comments