How do you cope with data classes with computed pr...
# mockk
d
How do you cope with data classes with computed properties?
Copy code
data class Animal(val type: String) {
  val isFavorite = type == "cat"
}
How do you set up the class in a test which just relies on its behavior, i.e. it's not the test for the class? Three approaches come to my mind: • Just construct the class explicitly and let the
isFavorite
property be actually computed. • Mock the class including all its properties (constructor and computed) • Use
spyk
and mock just the computed property (didn't try but I guess it should work)
m
I’d definitely go with approach 1). Mocking data classes is a code smell in general, and mocking them in tests that test other classes doesn’t seem like a good idea to me. Generally speaking, mocking is about driving object behaviors, while data classes are meant to hold data rather than behaviors
d
mocking is about driving object behaviors
Agree, but here it's IMO not that clear because
isFavorite
can be considered behaviour because it's computed (albeit simple)
m
here’s a more detailed explanation from Mockito’s guide on why mocking data classes (or value objects) is not a good idea
I agree with your point, but I also think that
isFavorite
in your case is kind of an edge case between “data” and “behavior” 🙂
d
That's the whole point of this example, that it's an edge case! And honestly I find it more clear if the test drives the behavior of the class exactly by mocking the behaviour instead of relying on the particular implementation. So for me the first option is kind of wrong. But so are the other two because I also agree that mocking data classes is a code smell. So what now? 🙂
m
good point 🙂 In an edge case like this I’d probably go with option 3) and mock just the computed property It seems to me like a clearer expression of the intent to mock just that, it kind of signals “I know mocking data classes is a bad practice, but this is not just a data class, it has behavior, and I want to mock just that”
also the fact that it’s a computed property rather than a function makes it probably even more of an edge case 🙂
d
Yeah, agree. It seems quite clear to me once I have written out all the possibilities 🙂
j
I'd say it depends on how complex the computation is. If most humans can guess what the result of the computation will be without looking at the implementation then I would not stub the behavior. In this case stubbing makes sense since its very rare to find someone who's favorite animal is a cat 🙂
😅 1
🤣 1
254 Views