I am using the builder pattern in my unit tests and I have come to a situation where I need to verify the behavior (with Moq verify) of a dependency that leaves inside the the builder.
The way I designed the builder, this dependency is hidden in the builder class for easier object creation. However, now my test method cannot access the mocked object for verification.
I thought about two different approaches, but not sure what would be the most common used in builder pattern:
Option 1: Expose mocks as a builder property.
//Setup
var equipment = equipmentBuilder
.AddDevice("Device1")
.Create();
//act
equipment.SomeMethod();
//Verify
equipmentBuilder.DeviceStubs.ElementAt(0).Verify(v => v.Method(), Times.Once);
or inject dependencies on the builder methods
//Setup
var deviceStub = new Mock<Device>();
deviceStub.Setup(x=>x.Name).Returns("Device1");
var equipment = equipmentBuilder
.AddDevice(deviceStub)
.Create();
//Act
equipment.SomeMethod();
//Verfiy
deviceStub.Verify(v => v.Method(), Times.Once);
For me the second approach looks more robust with things more isolated. However, the construction of the equipment objects will have more code. In case I have several test methods, this will be a lot of extra code.
What would you do? A third option maybe...
Thanks.
Aucun commentaire:
Enregistrer un commentaire