ambiguous references when mixing NUnit and NMock2 matchers
We're using NUnit (2.5.9) and NMock2 for unit testing and mocking. Both, however, have a matcher syntax that closely corresponds. When I do
using NUnit.Framework;
using NMock2;
And later on the following NMock2 code:
Expect.Once.On(database).Method("Create").
With(Has.Property("id", Is.EqualTo("012345678901")));
But also an NUnit assertion:
Assert.That(someValue, Is.EqualTo(54321));
Then VS (2008) will complain that 'Is' is an ambiguous reference between 'NUnit.Framework.Is' and 'NMock2.Is' (and same for 'Has').
Is there any way around this? It seems that both matchers have similar functionality anyway. Prefixing each matcher class with the full namespace of course works, but it makes tests significantly less readable.
开发者_高级运维Google searches for this issue have found no match at all, so my underbelly feeling is that i'm doing something very stupid.
You can avoid using the Nunit fluent syntax.
Assert.AreEqual(54321, someValue);
And then use aliases in conjunction.
using NMock2;
using Is = NMock2.Is;
using Has = NMock2.Has;
This will force your application to take the NMock versions of these classes. If you wanted to get to the NUnit ones, you would have to give a full name including namespace.
Another option to preserve both would be to use the following namespace declarations and aliases.
using NUnit.Framework;
using Is = NUnit.Framework.Is;
using NMock2;
using WithValue = NMock2.Is;
using Has = NMock2.Has;
Now you can use both fluent interfaces, but the code reads
Expect.Once.On(database).Method("Create").
With(Has.Property("id", WithValue.EqualTo("012345678901")));
Assert.That(someValue, Is.EqualTo(54321));
Interestingly enough NUnit also exposes a little class called Iz that you can use to avoid this naming collision with NMock2. So for example instead of:
Assert.That(someValue, Is.EqualTo(54321))
you can write
Assert.That(someValue, Iz.EqualTo(54321))
May not be the cleanest, but it doez work ;)
Use Namespace aliases if you need to use constraints. Eg.
using N = NUnit.Framework; using M = NMock2;
Then
Assert.That(someValue, Is.EqualTo(54321))would become
Assert.That(someValue, N.Is.EqualTo(54321))
精彩评论