gpt4 book ai didi

c# - 在 NUnit 中,如何为结构的属性比较指定容差?

转载 作者:行者123 更新时间:2023-12-04 18:02:11 24 4
gpt4 key购买 nike

我有以下 NUnit 测试,由于某种原因结构比较失败:

public struct Record
{
public double P1 { get; set; }
public double P2 { get; set; }
}

[TestFixture]
public class UnitTest
{
[Test]
public void PassingTest()
{
Assert.That(100, Is.EqualTo(99.99999999).Within(.0001));
}

[Test]
public void FailingTest()
{
Assert.That(new Record { P1 = 1.0, P2 = 100 },
Is.EqualTo(new Record { P1 = 1.0, P2 = 99.99999999 }).Within(.0001));
}

[Test]
public void AlsoPassesTest()
{
Assert.That(new Record { P1 = 1.0, P2 = 100 },
Is.EqualTo(new Record { P1 = 1.0, P2 = 100 }).Within(.0001));
}
}

问题(1):为什么structs comparison的测试会失败?问题 (2):如果结构比较测试失败是因为没有“深入”应用容差,我该如何设置才能通过结构比较测试?

最佳答案

看来你必须手写这个。像这样:

static class IsAlternatively
{
public static AlternativeEqualConstraint EqualTo(Record r)
{
return new AlternativeEqualConstraint(r);
}
}

class AlternativeEqualConstraint : NUnit.Framework.Constraints.Constraint
{
readonly Record expected;
double tolerance;

public AlternativeEqualConstraint(Record r)
{
this.expected = r;
}

public AlternativeEqualConstraint Within(double tolerance)
{
this.tolerance = tolerance;
return this;
}


public override bool Matches(object obj)
{
actual = obj;

if (!(obj is Record))
return false;

var other = (Record)obj;

return Math.Abs(other.P1 - expected.P1) < tolerance && Math.Abs(other.P2 - expected.P2) < tolerance;
}

public override void WriteDescriptionTo(NUnit.Framework.Constraints.MessageWriter writer)
{
writer.WriteExpectedValue(expected);
writer.WriteMessageLine("Expected within tolerance '{0}'.", tolerance);
}

public override void WriteActualValueTo(NUnit.Framework.Constraints.MessageWriter writer)
{
writer.WriteActualValue(actual);
}
}

当然可以这样使用:

  Assert.That(new Record { P1 = 1.0, P2 = 100.0, },
IsAlternatively.EqualTo(new Record { P1 = 1.0, P2 = 99.99999999, }).Within(.0001)
);

Assert.That(new Record { P1 = 1.0, P2 = 100.0, },
IsAlternatively.EqualTo(new Record { P1 = 1.0, P2 = 100.0, }).Within(.0001)
);

Assert.That(new Record { P1 = 1.0, P2 = 100.0, },
IsAlternatively.EqualTo(new Record { P1 = 1.0, P2 = 66.6, }).Within(.0001)
);

关于c# - 在 NUnit 中,如何为结构的属性比较指定容差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33299023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com