Also published on DZone
You use Dependency Injection (CDI) in your application and you want to unit test your Java classes without making it an integration test by using Weld of Arquillian. You use a Mocking framework like Mockito or EasyMock but still have trouble getting all your dependencies injected into the class because one or the injections is a String type or another final class.
org.mockito.exceptions.base.MockitoException: Cannot mock/spy class java.lang.String Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types You don’t want to change your code to make it more testable and you don’t want to add accessors to do this. Now you have trouble creating JUnit tests…
Create your own small injection utility method:
So if you have a class like this you want to test:
You can test it like this:
For other Injectables you can still use Mockito or your Mocking framework of choice but for final stuff you can do this. Fun and easy.