I am programming in Java SE using WELD-SE for dependency injection. Therefore, class dependencies look something like this:
public class ProductionCodeClass { @Inject private DependencyClass dependency; }
When writing a unit test for this class, I create a mock for DependencyClass , and since I donโt want to run a full CDI environment for every run that I run, I โenterโ the layout manually:
import static TestSupport.setField; import static org.mockito.Mockito.*; public class ProductionCodeClassTest { @Before public void setUp() { mockedDependency = mock(DependencyClass.class); testedInstance = new ProductionCodeClass(); setField(testedInstance, "dependency", mockedDependency); } }
The statically imported setField() method setField() I wrote myself in a class with the tools that I use when testing:
public class TestSupport { public static void setField( final Object instance, final String field, final Object value) { try { for (Class classIterator = instance.getClass(); classIterator != null; classIterator = classIterator.getSuperclass()) { try { final Field declaredField = classIterator.getDeclaredField(field); declaredField.setAccessible(true); declaredField.set(instance, value); return; } catch (final NoSuchFieldException nsfe) {
What I don't like about this solution is that I need this assistant over and over again in any new project. I already packaged it as a Maven project, which I can add as a test dependency to my projects.
But isnโt there anything ready in some other shared library that I miss? Any comments on my way of doing this in general?
source share