Pascal How
02/11/2018, 11:53 PMgildor
02/12/2018, 1:37 AMPascal How
02/12/2018, 10:29 AMCar
class with an extension function hadAccident()
because the original class did not have this method and it is from a third party library so we cannot add member functions
Then if another class ServiceCompany
takes a car
and a mechanic
as dependency and one of its methods does
fun organiseRepair() {
if(car.hadAccident) {
mechanic.doFullRepair()
} else {
mechanic.doMinimalCheck()
}
}
When testing with Mockito you would then want something like
fun givenCarHadAccident_whenOrganiseRepair_thenDoFullRepair() {
`when`(car.hadAccident).thenReturn(true)
serviceCompany.organiseRepair()
verify(mechanic).doFullRepair()
}
gildor
02/12/2018, 10:31 AMmechanic
?Pascal How
02/12/2018, 10:32 AMgildor
02/12/2018, 10:33 AMPascal How
02/12/2018, 10:34 AMclass ServiceCompany(val car:Car, val mechanic: Mechanic) {
fun organiseRepair() {
if(car.hadAccident) {
mechanic.doFullRepair()
} else {
mechanic.doMinimalCheck()
}
}
}
Car
is from a third party library and it does not have the hadAccident
method?gildor
02/12/2018, 10:35 AMfun Car.hadAccident() = this.accidents.size > 0
You can just do:
fun givenCarHadAccident_whenOrganiseRepair_thenDoFullRepair() {
val carWithAccident = Car(accidents = listOf(Accident()))
val serviceCompany = ServiceCompany(carWithAccident, mechanic)
serviceCompany.organiseRepair()
verify(mechanic).doFullRepair()
}
Pascal How
02/12/2018, 10:50 AMval car = Car()
(might be a bad example)
Then one way around that is to provide an interface and the class that implements that can provide a method wrapping the call to the extension function.
During test, you would then test the mock instance instead
Thanks! I saw these libraries but I did not think it was a good idea to use themgildor
02/12/2018, 10:53 AMcar
even if you mock hadAccident
.
So I really don’t see any reason to use mocked extension function in this caseserviceCompany
instead of testing serviceCompany
results, so it’s also bad practice imhohadAccident
would be member function I still suggest to use real instance of Car with proper data for cases when it’s possiblePascal How
02/12/2018, 11:10 AM