Reputation: 886
I'm new to C# so this might be a really dump question: I implemented IComparable in my class and want to test it with NUnit. But the CompareTo-Method is marked as private and thus not accessible from the test.
What's the reason for this and how can I fix this?
The IComparable:
public class PersonHistoryItem : DateEntity,IComparable
{
...
int IComparable.CompareTo(object obj)
{
PersonHistoryItem phi = (PersonHistoryItem)obj;
return this.StartDate.CompareTo(phi.StartDate);
}
}
The test:
[TestMethod]
public void TestPersonHistoryItem() {
DateTime startDate = new DateTime(2001, 2, 2);
DateTime endDate = new DateTime(2010, 2, 2);
PersonHistoryItem phi1 = new PersonHistoryItem(startDate,endDate);
PersonHistoryItem phi2 = new PersonHistoryItem(startDate, endDate);
Assert.IsTrue(phi1.CompareTo(phi2)==0);
}
Upvotes: 1
Views: 1037
Reputation: 120917
In C# an interface does not define accessors, so you can make your CompareTo
method public and change the explicit interface implementation from:
int IComparable.CompareTo(object obj)
To:
public int CompareTo(object obj)
Upvotes: 0
Reputation: 1874
I think the easiest way would be to use implicit interface implementation:
public class PersonHistoryItem : DateEntity, IComparable
{
...
public int CompareTo(object obj)
{
PersonHistoryItem phi = (PersonHistoryItem)obj;
return this.StartDate.CompareTo(phi.StartDate);
}
}
Upvotes: 1
Reputation: 5885
The main problem here is that you explicitly implements the CompareTo method, which only allows you to use it when you use your object as a IComparable object.
To correct the problem, specify the visibility as public and implement the CompareTo method not "explicitly" :
public class PersonHistoryItem : DateEntity,IComparable
{
...
public int CompareTo(object obj)
{
PersonHistoryItem phi = (PersonHistoryItem)obj;
return this.StartDate.CompareTo(phi.StartDate);
}
}
Upvotes: 0
Reputation: 8008
Your approach uses explicit interface implementation. That means that the interface methods will not show up on your class unless a cast is done.
Do this:((IComparable)phi1).CompareTo(phi2)
Upvotes: 0
Reputation: 1038710
var p1 = (IComparable)phi1;
var p2 = (IComparable)phi2;
Assert.IsTrue(p1.CompareTo(p2) == 0);
Upvotes: 1
Reputation: 233125
They are not private, they are just explicitly implemented. Declaring your variables as IComparable
should solve the problem:
[TestMethod]
public void TestPersonHistoryItem() {
DateTime startDate = new DateTime(2001, 2, 2);
DateTime endDate = new DateTime(2010, 2, 2);
IComparable phi1 = new PersonHistoryItem(startDate,endDate);
IComparable phi2 = new PersonHistoryItem(startDate, endDate);
Assert.IsTrue(phi1.CompareTo(phi2)==0);
}
Upvotes: 3