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 PersonServiceProxyTest {
11+ @ Test
12+ public void testService () {
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 testFixedValue () throws Exception {
25+ //given
26+ Enhancer enhancer = new Enhancer ();
27+ enhancer .setSuperclass (PersonService .class );
28+ enhancer .setCallback ((FixedValue ) () -> "Hello cglib!" );
29+ PersonService proxy = (PersonService ) enhancer .create ();
30+
31+ //when
32+ String res = proxy .sayHello (null );
33+
34+ //then
35+ assertEquals ("Hello cglib!" , res );
36+ }
37+
38+ @ Test
39+ public void testMethodInterceptor () 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 cglib!" ;
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 cglib!" , proxy .sayHello (null ));
56+
57+ int lengthOfName = proxy .lengthOfName ("Mary" );
58+ assertEquals (4 , lengthOfName );
59+ }
60+
61+ }
0 commit comments