Monday, April 16, 2012

Rhino Mocks Constraints

Constraints are a way to verify that a method's arguments match a certain criteria. Rhino Mocks includes a number of built-in constraints, and allows you to define you own custom ones, which will integrate cleanly into the framework. You specify constraints on method arguments using the following syntax:

   Is.Anything(), Is.TypeOf(typeof(SomeType))).Return(null).

You need to pass the exact same number of constraints as the number of arguments of the method. When a method is called during replay state, Rhino Mocks evaluates each constraint against the parameter in the same index, and accepts the method if all the constraints were met. As a note, I got the idea of the current constraints syntax from NMock2, as it is much leaner approach to create constraints.

Rhino Mocks' built in constraints:

Rhino Mocks Constraints

ExampleAccepted Values

Rejected Values
IsAnythingIs.Anything()Anything at all {0,"","whatever",null, etc}Nothing Whatsoever
Not EqualIs.NotEqual(3)null, "bar"3
NullIs.Null()null5, new object()
Not NullIs.NotNull() new object(), DateTime.Nownull
Type OfIs.TypeOf(typeof(Customer)) or Is.TypeOf<Customer>()myCustomer, new Customer()null, "str"
Greater ThanIs.GreaterThan(10)15,532,10
Greater Than Or EqualIs.GreaterThanOrEqual(10)10,15,439,3
Less ThanIs.LessThan(10)1,2,3,910,34
Less Than Or EqualIs.LessThanOrEqual(10)10,9,2,034,53,99
PropertyEqual To ValueProperty.Value("Length",0)new ArrayList()"Hello", null
NullProperty.IsNull("InnerException")new Exception("exception without inner exception") new Exception("Exception with inner Exception", new Exception("Inner")
Not NullProperty.IsNotNull("InnerException")new Exception("Exception with inner Exception", new Exception("Inner") new Exception("exception without inner exception")
ListIs In List [the parameter is a collection that contains this value] List.IsIn(4)new int[]{1,2,3,4}, new int[]{4,5,6}new object[]{"",3}
One Of [parameter equal to one of the objects in this list]List.OneOf(new int[]{3,4,5}) 3,4,59,1,""
EqualList.Equal(new int[]{4,5,6})new int[]{4,5,6}, new object[]{4,5,6} new int[]{4,5,6,7}
TextStarts WithText.StartsWith("Hello")"Hello, World", "Hello, Rhino Mocks""", "Bye, Bye"
Ends WithText.EndsWith("World")"World","Champion Of The World" "world", "World Seria"
ContainsText.Contains("or")"The Horror Movie...", "Either that or this""Movie Of The Year"
Like [Perform regular expression validation]Text.Like("rhino|Rhinoceros|rhinoceros") "Rhino Mocks", "Red Rhinoceros""Hello world", "Foo bar", Another boring example string"

QR: Inline image 1

Posted via email from Jasper-Net