Right approach to test convert-like methods
Suppose i have lots of classes like this (Foo1, Foo2 ..)
class Foo
{
public int F{get; set;}
public Bar ConvertToBar ()
{
return new Bar(){ B = this.F*10 };
}
}
all they have in common is ConvertToBar() method.
I have two approaches to unit-test this method:
Call convert to ConvertToBar () and check all it's properties (I have to do it in all tests for each Foo like class)
Bar bar = foo.ConvertToBar (); Assert.AreEqual (expectedValue, bar.Property); ...
Write helper method that compares two Bar instances and then use it like this:
Bar expectedBar = new Bar () Assert.True( barCompareMethod (expectedBar, foo.ConvertToBar ());
What will be the best way to write unit-test for 开发者_StackOverflow中文版this method?
Does it make sense for Bar
itself to be IEquatable<Bar>
? If so, I'd implement that in your production code, rather than having a helper method. Then you can just use Assert.AreEqual(expectedBar, actualBar)
.
As Jon Skeet suggests, implementing custom equality on Bar is a great idea as long as you understand how to steer clear of Equality Pollution.
For semantic comparison, you can use AutoFixture's SemanticComparison library, which would enable you to write a assertion like this:
var expected = bar1.AsSource().OfLikeness<Bar>();
expected.ShouldEqual(bar2);
The ShouldEqual method is a custom assertion that will compare each property (matched by name) and only succeed when all properties are equal; otherwise it will throw a descriptive exception.
I'm not sure there is a best way.
the first is a bit more readable in my opinion. You may want to experiment with NUnit's property constaints
Assert.That(someObject, Has.Property("Version").EqualTo("2.0"));
the second is a bit more work in that you'd have to define Equals in the Bar classes (might be a problem if you do not have source edit access). But it would be preferable, if a large number of properties need to be asserted on.
精彩评论