javakaffee

Just another weblog about (web) development technologies like spring, tapestry, jersey, jsf, hibernate and more

September 12, 2006

JUnit test spring managed and proxy’ed beans

Filed under: development, java — martin.grotzke @ 9:00 am

When you have some spring managed bean MyBean and use spring features like e.g. declarative transaction management, spring will create a proxy object for your bean instance.
When you use springs beanfactory in junit and try to downcast the object to the bean class itself (and not to some implemented interface), you’ll get a ClassCastException (telling you that you have s.th. like $Proxy$39).
Some example code: MyBean myBean = (MyBean)beanFactory.getBean("myBean");. The ClassCastException is probably caused by junits dynamic classloading together with the proxy object.

The solution is to use an interface like MyInterface that is implemented by MyBean. Then you can downcast the proxy object to the interface: MyInterface myBean = (MyInterface)beanFactory.getBean("myBean");.

Another solution is described in this posting in the spring forum: it suggests to disable junits dynamic classloading by extending the with those classes that shouldn’t be dynamically loaded.

Some more information about junits dynamic classloading can be found in the junit FAQ.

1 Comment »

  1. I just found a free online chapter concerning proxies from the book Java Reflection in Action.

    Comment by martin.grotzke — September 12, 2006 @ 9:10 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image

Powered by WordPress