kse*_*een 7 .net c# nunit unit-testing winforms
我正在进行测试,但如果失败,我不知道为什么:
Proj.Tests.StatTests.GetResults_RegularPage_ReturnListOfResults:
Expected and actual are both <System.Collections.Generic.List`1[Proj.Classes.StatResult]> with 50 elements
Values differ at index [0]
Expected: <test;98318>
But was: <test;98318>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,值是相同的.这是一些代码:
public class StatResult
{
public string word { get; set; }
public UInt64 views { get; set; }
public override string ToString()
{
return String.Format("{0};{1}", word, views);
}
}
[Test]
public void GetResults_RegularPage_ReturnListOfResults()
{
// Arrange
WordStat instance = new WordStat(Constants.WordStatRegularPage);
// Act
List<StatResult> results = instance.GetResults();
// Assert
Assert.AreEqual(results, new List<StatResult>
{
new WordStatResult { word ="test", views = 98318},
new WordStatResult { word ="test board", views = 7801},
//... I shorted it
}
Run Code Online (Sandbox Code Playgroud)
}
我尝试了很多方法甚至将测试样本放入课堂,但无论如何它都无法正常工作.请帮忙!
我可以看到这两个引用引用了具有相同属性的对象,但这不是在这里测试的内容.它检查它们是指向同一个对象还是它们是相同的.您的StatResult类不会覆盖Equals/ GetHashCode,因此具有相同值的两个对象将被视为"不同"以进行测试.
您应该覆盖Equals并且GetHashCode为了使两个对象被认为是相等的.我还建议使类型不可变,以及遵循属性的正常.NET命名约定:
public sealed class StatResult : IEquatable<StatResult>
{
public string Word { get; private set; }
public UInt64 Views { get; private set; }
public StatResult(string word, ulong views)
{
this.word = word;
this.views = views;
}
public override string ToString()
{
return String.Format("{0};{1}", word, views);
}
public override int GetHashCode()
{
int hash = 23;
hash = hash * 31 + Word == null ? 0 : Word.GetHashCode();
hash = hash * 31 + Views.GetHashCode();
return hash;
}
public override bool Equals(object other)
{
return Equals(other as StatResult);
}
public bool Equals(StatResult other)
{
return other != null &&
this.Word == other.Word &&
this.Views == other.Views;
}
}
Run Code Online (Sandbox Code Playgroud)
你的建筑只会改为:
new StatResult("test", 98318),
new StatResult("test board", 7801),
Run Code Online (Sandbox Code Playgroud)
(同样在您的生产代码中).