Unit testing a class with autowired notation using Junit and EasyMock?
You can reflectively inject dependencies directly into the field using ReflectionTestUtils
, e.g.
ReflectionTestUtils.setField( testInstance, "fieldName", fieldValue );
Some would argue that it's preferable to add a package-visible setter method to the class anyway, used solely by the tests. Alternatively, use autowired constructors, rather than autowired fields, and inject the test dependencies into that.
Although it is possible to set these fields via reflection, doing so will prevent your development tools from finding usages of these fields, and make it harder for you to refactor SomeClassToTest
in the future.
It would be better to add public setters for these fields, and place the @Autowired
annotations on these instead. Not only does this avoid reflection, but it also clarifies the external interface of the class and ensures that your unit test uses just this interface. I see that SomeClassToTest
already implements the SomeOtherClass
interface, and I assume that clients of SomeClassToTest
only use this interface, so there is little danger in making the setters on SomeClassToTest
public.
Better still, use constructor injection and make the fields final. You can still use @Autowired
on the constructor arguments.