lundi 30 mars 2015

How to test 2 methods with common logic?

Let's say that I have 2 public methods:



func didSelect(data: Data) {
// do something

self.view.showText(textForData(data))
}

func didDismiss(data: Data) {
if data.isSomething {
self.view.showText(textForData(data))
}

...
}

private func textForData(data: Data): String {
var text: String

if data.distance == nil {
text = "..."
} else if data.distance < 1000 {
text = "\(data.distance) m"
} else {
text = "\(data.distance / 1000) km"
}

return text
}


Both of them depend on the formatting logic of textForData.


textForData has (with this minimized implementation) 3 possible cases. If I do test every possible case for both of my public functions, I'll end up with 6 test methods, and 3 of them would also be testing the same logic that was already tested by the other 3.


What's the proper way of testing this?


Ps.: I could write a separate test for textForData and in the tests for the public methods I assert that the textForData is called, but that seems to break the encapsulation of my class and I don't want to make the testForData public. I also wouldn't like to make a separate class just for my textForData logic, because I would end up creating too many dependencies for this current class, and that logic doesn't seem to fit anywhere else besides in this class.


Aucun commentaire:

Enregistrer un commentaire