Friday, March 28, 2014

Set a private field on a class you need to Unit Test

Well, of course, you could make your field with default access, or you can add some boilerplate setter, or you could fancy whipping up a utility using reflection, but spring-test has already thought of that.

Let's say you want to test your DonkeyController:

This is how you can easily set the private field donkeyDAO, without changes in the class under test:

ReflectionTestUtils is in spring-test:

Cheers!