I\'ve been trying to adopt the Cake Pattern but I\'m having difficulties adapting to this programming styles, especially where unit tests are concerned.
Lets assume that
I have found a way to use Scalamock with Scalatest for the purpose of unit testing 'Cake Pattern' modules.
At first, I had many problems (including this one), but I believe the solution I present below is acceptable. If you have any concerns, please let me know.
This is how I would design your example:
trait VetModule {
def vet: Vet
trait Vet {
def vaccinate(pet: Pet)
}
}
trait PetStoreModule {
self: VetModule =>
def sell(pet: Pet)
}
trait PetStoreModuleImpl extends PetStoreModule {
self: VetModule =>
def sell(pet: Pet) {
vet.vaccinate(pet)
// do some other stuff
}
}
The tests are then defined as following:
class TestPetstore extends FlatSpec with ShouldMatchers with MockFactory {
trait PetstoreBehavior extends PetStoreModule with VetModule {
object MockWrapper {
var vet: Vet = null
}
def fixture = {
val v = mock[Vet]
MockWrapper.vet = v
v
}
def t1 {
val vet = fixture
val p = Pet("Fido")
(vet.vaccinate _).expects(p)
sell(p)
}
def vet: Vet = MockWrapper.vet
}
val somePetStoreImpl = new PetstoreBehavior with PetStoreModuleImpl
"The PetStore" should "vaccinate an animal before selling" in somePetStoreImpl.t1
}
Using this setup, you have the 'disadvantage' that you have to call val vet = fixture in every test you write. On the other hand, one can easily create another 'implementation' of the test, e.g.,
val someOtherPetStoreImpl = new PetstoreBehavior with PetStoreModuleOtherImpl