When using Mockito 1.9.x I have been using Whitebox
to set values of fields to "inject" mocks. Se example below:
@Before public void setUp() { eventHandler = new ProcessEventHandler(); securityService = new SecurityServiceMock(); registrationService = mock(RegistrationService.class); Whitebox.setInternalState(eventHandler, "registrationService", registrationService); Whitebox.setInternalState(eventHandler, "securityService", securityService); }
I really like this approach, but now that I tried to upgrade to Mockito
2.2.7
I noticed (or rather, my IDE noticed and told me quite a few times) that Whitebox was no longer to be found in Mockito.
I have found one alternative, that can work as a replacement, and that is org.powermock.reflect.Whitebox
, the problem with that is that I get another dependency (Powermock), just to use Whitebox.
Powermock
also have a class named Whitebox
, but unfortunately it looks as if it can not be used with Mockito 2.2.x
Is there any good alternatives in Mockito that I can use to manually "inject" fields, now that Whitebox
is no longer available?
I wrote in a comment in response to the post made of @JeffBowman. In short I chose to copy the code of WhiteBox, and use that, since it is used in most of the test cases and the class does not have dependencies to other classes. It was the fastest path to solve this issue.
Note The solution that @bcody suggest is a better alternative, if you are using spring, it ads no extra code for you to maintain. I got that information to late :(
Whitebox provides various utilities for accessing the internals of a class. These utilities include instantiating private classes and invoking private methods by using reflection. Whitebox is a utility intended for tests.
invokeMethod. Invoke a private or inner class method in that is located in a subclass of the instance. This might be useful to test private methods. Use this for overloaded methods.
Method With No Arguments but With Return Value. As a simple example, let's mock the behavior of a private method with no arguments and force it to return the desired value: LuckyNumberGenerator mock = spy(new LuckyNumberGenerator()); when(mock, "getDefaultLuckyNumber"). thenReturn(300);
If you are using Spring (the spring-test library specifically), you can simply use ReflectionTestUtils.setField
instead of Whitebox.setInternalState
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With