在NUnit中,如何指定struct的属性比较容差?

时间:2015-10-23 09:28:38

标签: c# struct nunit equality

我有以下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):为什么结构比较的测试失败?问题(2):如果结构比较的测试失败,因为公差没有“深度”应用,我怎么设置东西以便结构比较的测试通过?

2 个答案:

答案 0 :(得分:1)

看来,你必须手工编写。像这样:

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)
    );

答案 1 :(得分:0)

你可以为struct的属性做两个单独的断言:

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

我认为Tolerance不适用于整个结构,因为你在整个结构上设置它。

无论如何,根据测试的性质,您可以考虑将此测试分成两个独立的测试,特别是如果只有一个属性必须具有容差而另一个需要精确。