Mocking lombok Value classes.

3,222 views
Skip to first unread message

Tomas Herman

unread,
Oct 23, 2015, 1:29:24 PM10/23/15
to Project Lombok
Hey guys,

i was wondering, is it possible to mock @Value classes with mockito? I am getting this error: 
org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class com.wikidi.Ticker
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

//Ticker looks like this:
@Value
@Builder
public class Ticker {
    private final double buyPrice;
    private final double sellPrice;
}

Is this a known thing? I am using gradle to run tests.

Reinier Zwitserloot

unread,
Oct 23, 2015, 1:31:06 PM10/23/15
to Project Lombok
You can stick @NonFinal on it. Note that Mockito and co are bad because they ruin your main code base just to enable nicer tests. I'm all for nicer tests, but not if it means my main code base suffers as a result.

The whole point of value classes is that they are final. Making them nonfinal is a visible artefact, means you have to put really hacky comments on it:

/** This class is not final but please consider it final. Stuff breaks if you extend it. Thanks! */

and thus, in our opinion a bad idea and not something we'll ever specifically cater to.

Ryan Schmitt

unread,
Oct 23, 2015, 3:51:11 PM10/23/15
to project...@googlegroups.com
Why would you want to mock a @Value class in the first place? Value classes aren't supposed to have any behavior; there shouldn't be anything to mock.

--
You received this message because you are subscribed to the Google Groups "Project Lombok" group.
To unsubscribe from this group and stop receiving emails from it, send an email to project-lombo...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ryan Schmitt

unread,
Oct 23, 2015, 3:52:10 PM10/23/15
to project...@googlegroups.com
What deleterious effect do you think Mockito has on the production-side code? I've certainly seen it misused and abused, but I'm not sure what inherent downsides you think it has.

--

Martin Grajcar

unread,
Oct 23, 2015, 9:40:07 PM10/23/15
to project...@googlegroups.com
I surely think that value classes can have a lot of behaviour (e.g. LocalDate@plus(int days) is complicated enough to deserve a test). But there should be no need to mock them as they should be easy to create and to observe.

Compromising classes in order to make then easier to test without improving the overall structure is surely bad. In case of @VisibleForTesting it's no big deal, but with @NonFinalForTesting it may be as you lose visibility guarantee.

IIRC PowerMock uses some magic to work with final classes too.
Reply all
Reply to author
Forward
0 new messages