CSharp example of using Rhino Mock constraints
Jan 13, 2013 00:00 · 301 words · 2 minute read
What is Rhino Mock constraint?
constraint help us to check that method arguments or properties values are matching with our criteria or not [ more info ].
Example
Injecting dependencies into production code is not always easy and simple . Sometimes you come across with other scenarios such as below
public void SetupAndRegisterNewDevice(int id,string name) {
Device device=new Device(){Id = id,Name = name};
_deviceManager.Add(device);
_deviceManager.AddedSucessfully = true;
_deviceManager.special = _deviceManager.IsSpecialProduct(device) ? "Special" : "Not Special";
}
If you want to assert that the Add method called with below code
[Test]
public void Given_Name_Id_When_SetupAndRegisterNewDevice_then_AddSameDeviceType() {
//Arrange
var deviceManager = MockRepository.GenerateMock<IDeviceManager>();
var machine = new Machine(deviceManager);
var device = new Device { Id = 1, Name = "printer" };
//Act
machine.SetupAndRegisterNewDevice(device.Id,device.Name);
//Assert
deviceManager.AssertWasCalled(x => x.Add(device));
}
It will be failing as the device instances are not the same. In this case we can use constraint and validate the input values of the Add method with Matches constraint.
deviceManager.AssertWasCalled(x => x.Add(Arg<Device>.Matches(y=>y.Id==device.Id && y.Name==device.Name)));
If we don’t care about the input type and just want to check the code flow we can come up with something like this
deviceManager.AssertWasCalled(x => x.Add(Arg<Device>.Is.Anything));
Or just check that it is it null or not
deviceManager.AssertWasCalled(x => x.Add(Arg<Device>.Is.NotNull));
Text constraint
It is also possible to evaluate the values of properties that match with your desire pattern or not . For instance to check if the Special property has “Special” term in its value you can write
deviceManager.AssertWasCalled(x => x.special = Arg<string>.Matches(Rhino.Mocks.Constraints.Text.Like("Special")));
List constraints
Rhino constraints also help us to check the list values.
public void RegisterDevices(List<Device> devices) {
_deviceManager.AddAll(devices);
}
We can check that if the passing list matches with our criteria or not
deviceManager.AssertWasCalled(x => x.AddAll(Arg<List<Device>>.List.IsIn(device1)));
deviceManager.AssertWasCalled(x => x.AddAll(Arg<List<Device>>.List.Count(Rhino.Mocks.Constraints.Is.Equal(3))));
deviceManager.AssertWasCalled(x => x.AddAll(Arg<List<Device>>.List.ContainsAll(deviceList)));
Download
Feel free to download the source code of this example from my [ GitHub ]