Treecj
Treecj

Reputation: 427

Mock a closure that manipulates a private field of the unit under test

I have the following code in my unit under test:

someDependency.doSomething(element -> {
    privateFieldOfUnitUnderTest += element;
});

Some dependency (which I mocked with mockito) calls the method doSomething (in the real code it's doing some async call) with a lambda function callback that modifies a private field of the unit under test. My question is how to test this properly using mockito (and without using powermocking techniques).

I want the mocked method doSomething to call the callback with some data provided by the unit test.

Upvotes: 0

Views: 1236

Answers (3)

Timothy Truckle
Timothy Truckle

Reputation: 15622

A UnitTest verivies the public observable behahior of the code under test (cut).

If the code snipped in your post is part of that cut then you have to verify that the method someDependency.doSomething() is called with the expected parameter:

// prepare mocks for dependencies
// prepare cut
// execute tested public method in cut
verify(dependency).doSomething(EXPECTED_SUM_OF_ELEMENT_AND_PRIVATE_PROPERTY_VALUE); 

Upvotes: 0

Dmytro Maslenko
Dmytro Maslenko

Reputation: 2297

If you mocked someDependency all what you can control for doSomething() is passing and returned data. The implementation of doSomething() is missed. It means the given functional interface will not be triggered inside doSomething(). It means even if you can control element it will not be involved.

I see the next possible solution:

  • Work with spy of someDependency
  • Call real doSomething()
  • Have someDependency.getElement() which can be mocked in your test
  • doSomething() should be reworked to work with getElement()

Upvotes: 2

jfneis
jfneis

Reputation: 2197

Try:

Mockito
  .doAnswer(i -> privateFieldOfUnitUnderTest += i.getArgument(0, Integer.class))
  .when(someDependency).doSomething(Matchers.any());

I didn't test it, but should work as expected.

Upvotes: 1

Related Questions