2008/10/06

Rhino.Mocks 3.5: The new generic list constraint.

Oren Eini has finally released Rhino.Mocks 3.5 RTM. As written in Oren's article (many thanks to him for the credits), I had submitted some time ago a patch, which adds a new useful constraint for generic collections. Some explanations are perhaps needed:

Suppose that you are setting up some expectation on a method that takes a collection as parameter: a list of strings, for example.
public interface IFoo
{
bool DoSomething(List<string> values);
}
With Rhino.Mocks 3.4, you can specify a constraint on the input collection. For instance, you can verify that the fifth element of the collection has the value "Hello".
Expect.Call<bool>(mockFoo.DoSomething(null))
.IgnoreArguments()
.Constraints(List.Element(4, Is.Equal("Hello"))
.Return(true);
Unfortunately, the List.Element method can only take an Int32 as first parameter. Thus, it makes the constraint only usable with Int32-indexed collections, such as lists and arrays. It is a shame if your parameter is a dictionary.

That's why I have written a new abstract constraint (KeyedListElement) and overriden the List.Element with a new generic method. The usage is very similar. It is actually a kind of generalization of the former method.
public interface IFoo
{
bool DoSomething(Dictionary<string, string> values);
}
Expect.Call<bool>(mockFoo.DoSomething(null))
.IgnoreArguments()
.Constraints(List.Element<string>("Value1", Is.Equal("Hello"))
.Return(true);
The example above defines a constraint on the parameter (a dictionary of strings keyed by strings). The value at index "Value1" must be equal to "Hello". Note the generic signature of the method, which specifies the type of the key.

Hope it helps!

No comments: