我有以下课程:
public class Range<T> where T : IComparable<T> {
public T Minimum { get; set; }
public T Maximum { get; set; }
public Range(T minimum, T maximum) {
Minimum = minimum;
Maximum = maximum;
}
public Boolean Contains(T value) {
return (Minimum.CompareTo(value) <= 0) && (value.CompareTo(Maximum) <= 0);
}
}
我正在使用XUnit来创建我的单元测试......
我应该如何测试包含T?的包含方法?
答案 0 :(得分:4)
如前所述,您可以使用int来测试它,它可能看起来像这样:
var range = new Range<int>(minimum: 3, maximum: 7);
Assert.IsTrue(range.Contains(5));
答案 1 :(得分:1)
你需要创建一个IComparable的实例并且为了彻底(真正的单元测试)我会建议一个能够验证调用的模拟库。我可能会使用像Moq这样的东西。您将需要一个实现该接口的对象,您可能已经拥有该对象,或者您可以创建一个没有实际实现的测试对象。</ p>
public class YourObject : IComparable<YourObject>
{
public virtual int CompareTo(YourObject other)
{
throw new NotImplementedException();
}
}
为了保持一致性,我会稍微改变你的Range代码:
public class Range<T> where T : IComparable<T>
{
public T Minimum { get; set; }
public T Maximum { get; set; }
public Range(T minimum, T maximum)
{
Minimum = minimum;
Maximum = maximum;
}
public Boolean Contains(T value)
{
return (Minimum.CompareTo(value) <= 0) && (Maximum.CompareTo(value) >= 0);
}
}
最终结果是相同的,但它在设置模拟时使事情变得容易一些。或者你可以带着价值。比较两个账户。无论哪种方式,它都会增加一点点的一致性。
测试代码看起来有点像这样:
var min = new Mock<YourObject>();
var max = new Mock<YourObject>();
var val = new Mock<YourObject>();
var range = new Range<YourObject>(min.Object, max.Object);
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
Assert.True(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(0);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
Assert.True(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(0);
Assert.True(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
Assert.False(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
Assert.False(range.Contains(val.Object));
现在您正在测试Range类的Contains方法,而不是对象在调用CompareTo时返回正确值的能力。
快乐的编码!