Tuesday, December 4, 2012

Spring, Autowire and EasyMock

I've been stalling on writing a number of tests I needed because I was caught up on how easily inject a Mock  into a Service that I wanted to test. The problem  was that I didn't want to go to the trouble of cooking up a separate spring context just for tests not to mention I couldn't rely on data in the DB for the DAO to utilize      after all the point of EasyMock is... EASY!  Well that avoiding writing that test that needed a mock finally bit me when some fast refactoring caused something fail because of the lacking test. That's what ya get, right?

After a good deal of hunting I come across a simple solution that I am surprised was so hard to find...

ReflectionTestUtils.setField(serviceYourTesting, "autowireBeanName", yourMock);

That's it! No, really.  OK OK, that's not all you have to do. You are messing with the Service Beans properties so if you have other tests elsewhere that expect that mock object to not be a mock object you'll have to undo what you did.  This isn't such a hassle though. simply call the following and stash that object to restore after you done with the mock.

Object saveBean = ReflectionTestUtils.getField(serviceYourTesting, "autowireBeanName");

I would suggest wrapping your test in a try/finally so you can make sure that the original bean value is set back before the tests concludes. If you don't do this other tests that expect the original bean may fail.

Happy Spring Mocking!

No comments:

Post a Comment