Reputation: 6431
Consider this example:
case class Home(description: String)
case class Person(age: Int, race: String, home: Home)
def age(p: Person): Person = {
val newAge = p.age + 1
p.copy(age = newAge, home = if (newAge == 18) Home("Under the bridge") else p.home)
}
it("Should move on 18th birthday") {
val person18yrs = age(Person(17, "Caucasian", Home("With parents")))
person18yrs shouldBe Person(18, "Caucasian", Home("Under the bridge"))
}
Now if I want to test the method age
, I need to fill the field race
even though the method age
doesn't discriminate the person
object based on it's race. It's only pass-through parameter. In this trivial example, it's not so much work, but when i work with two fields in a 20-field class hierarchy, I'm not happy. And I want to be happy. So I start to look around for some solution.
One solution might be to fill the empty fields with nulls. But the downside is if I then change the implementation, it would convert test classes compile error to tests failure. And I still need to write these nulls.
The other solution might be to just create the methods so they accept and return the parameters with which they interact. The downside is that I need to return tuples, which lack the name or I need to create some classes that encapsulate the method parameters and return types.
Or maybe the smart folks of stackoverflow do have some other solution, that half-blind eye of my intelligence cannot see. :-)
Upvotes: 1
Views: 59
Reputation: 11274
Create one completely filled person as a prototype, and then just create copies with the values that are relevant to your specific test case.
val protoype = Person(16, "Caucasian", Home("With parents"))
val person18yrs = age(protoype.copy(age = 17))
Upvotes: 1
Reputation: 12852
You could define factories with the same names as your case classes but fewer arguments, and have them create corresponding objects to which you pass default arguments, for example:
case class Person(age: Int, race: String, home: Home)
def Person(age: Int): Person = Person(age, "", Home(""))
Access to these factories could be limited to the test suite in order to avoid that they are used in non-rest-related code of your application.
Upvotes: 0