Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...