Reputation: 4302
As titled.
I have a class that implement IComparable which need for sorting. I wrote all unit testing against all methods. But then is it make sense to write a unit test to check does it implement IComparable?
Because with the interface when sorting in UI it won't work. But compile it will still work. So if I have such test case, it can be catch if anyone removed that interface.
My class is something like:
public class ComparableCustomType: IComparable
{
private readonly someFields;
public ComparableCustomType(AnotherBusinessObject obj)
{
//Do some parsing against the obj
}
public int CompareTo(object obj)
{
//Some custom sorting logic
}
}
Basically my test case will be:
[TestMethod]
public void CompareTo_IsImplementIComaparable()
{
IComparable comparable = Isolate.Fake.Instance<ComparableCustomType>();
Assert.AreNotEqual(null, comparable);
}
EDIT: This is how I use this property....(or I should say that's how the person use this property...)
public class CustomItem{
private AnotherBusinessObject anotherBusinessObj = null
public CustomItem(AnotherBusinessObject obj)
{
this.anotherBusinessObj = obj;
}
public ComparableCustomType {
get { return new CamparableCustomType(this.anotherBusinessObj); }
}
public string SomeOtherProperty {get;set;}
publci int AnotherProperty {get;set;}
}
public ObservableCollection<CustomItem> MyCustomCollection {get;set;}
Then this collection will databinds to my GridView.... so it will automatically generates all columns.....
Upvotes: 2
Views: 894
Reputation: 13350
To quickly summary my answer, I say no, it doesn't make much sense to write a unit test to check what a class implements/inherits. IMO, unit tests should be written to test logic/functionality, not type. That's pretty much like writing a test to make sure you can instantiate a constructor. Usually something like that is overkill and I believe that this case is overkill as well.
Your code should be checked at compile time. You can apply this constraint when the object is instantiated (if this is possible for the way you're using your objects).
Let's say that your class that implements IComparable
is called FooComparable
:
IComparable foo = new FooComparable();
Likewise, if you have already instantiated the object and it's sole function isn't necessarily an IComparable
object you could apply a couple other constraints. Let's say maybe you have your FooComparable
and you want to make sure it's IComparable
before binding it to a control, you could do something like this:
IComparable dataSource = fooObj;
If you try this and FooComparable does NOT implement IComparable, the compiler will complain. Maybe you should provide a code example of how you're using the class so we could provide more suggestions.
Upvotes: 6
Reputation: 13709
I would say don't test anything that the compiler will catch for you. Since you have a case that the compiler won't catch, it seems like it would be legit to create a UT for it.
Upvotes: 6