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

标签 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):为什么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/

相关文章:

c - 使用 malloc 分配结构数组

c - 结构类型数组,C错误

c# - 有没有办法使用带有可选参数的 NUnit TestCase 属性

c# - 为两个变更集之间的新/修改代码获取 resharper 问题

c# - 在 C# 中解决无限递归

c - 从结构中的二维数组中释放动态分配的内存

c# - 通过使用 [Setup] 方法中的代码输出当前测试的名称

f# - 使用Nunit公开F#测试用例方法以进行单元测试

c# - 不使用 Microsoft.AspNet.Identity.EntityFramework 的自定义 Asp.net mvc 5 身份验证

c# - 当角色可以组合到其他角色时,如何从列表中获取所有角色组合