我有一个用列表构建的深层树结构,包含列表和浮点数。 我想在这样的结构上做出断言,而不能为浮点数使用delta。我的问题是,使用失败断言的输出是不够的,因为需要一个或两个额外的小数。我必须猜测这些小数值才能继续。
using System.Collections;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestAssertLab
{
public class List : ArrayList {
public List(params object[] list) {
AddRange(list);
}
public override bool Equals(object other) {
List l = other as List;
if (l != null) {
if (Count != l.Count) return false;
return !l.Cast<object>().Where((t, i) => !this[i].Equals(t)).Any();
}
return false;
}
public override string ToString() {
string s = this.Cast<object>().Aggregate("", (current, item) => current + (item + ","));
return "[" + s.TrimEnd(',') + "]";
}
}
[TestClass]
public class AssertLab
{
public List z(params object[] l) {
return new List(l);
}
[TestMethod]
public void TestFails() {
List expected = z(0.1428571f, z(101, 102));
List actual = z(1/7.0f, z(101, 102));
Assert.AreEqual(expected, actual);
// output: Assert.AreEqual failed. Expected:<[0.1428571,[101,102]]>. Actual:<[0.1428571,[101,102]]>.
}
[TestMethod]
public void TestOK()
{
List expected = z(0.142857143f, z(30101, 30102));
List actual = z(1 / 7.0f, z(30101, 30102));
Assert.AreEqual(expected, actual);
}
}
}
答案 0 :(得分:3)
您可以将它们转换为十进制:
(Decimal) 0.1428571f == (Decimal)(1 / 7.0f)