Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I use instead of Whitebox in Mockito 2.2 to set fields?

When using Mockito 1.9.x I have been using Whiteboxto 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?


Solution

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 :(

like image 283
emanciperingsivraren Avatar asked Oct 27 '16 09:10

emanciperingsivraren


People also ask

What is Whitebox in Junit?

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.

What is the use of Whitebox invokeMethod?

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.

How do I use mock private Powermock?

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);


1 Answers

If you are using Spring (the spring-test library specifically), you can simply use ReflectionTestUtils.setField instead of Whitebox.setInternalState

like image 90
bcody Avatar answered Sep 24 '22 07:09

bcody