How can I use NUnit's EqualTo().Within() constraint with a custom data type?

只谈情不闲聊 提交于 2019-12-12 14:17:42

问题


I love NUnit's constraint-based API. I often use floating point comparison like this:

double d = foo.SomeComputedProperty;

Assert.That(d, Is.EqualTo(42.0).Within(0.001));

Very readable!

However, if I have a custom class whose equality depends on floating point comparison:

class Coord
{
  Coord(double radius, double radians)
  {
    this.Radius = radius;
    this.Radians = radians;
  }

  double Radius { get; }
  double Radians { get; }

  public override bool Equals(Object obj)
  {
    Coord c = obj as Coord;
    if (obj == null || c == null) return false;

    return c.Radians == this.Radians && c.Radius == this.Radius;
  }
}

I would like to write my tests like this:

Coord reference = new Coord(1.0, 3.14);

// test another Coord for near-equality to a reference Coord:
Assert.That(testCoord, Is.EqualTo(reference).Within(0.001));

Is it at all possible to use NUnit like this?

来源:https://stackoverflow.com/questions/31752407/how-can-i-use-nunits-equalto-within-constraint-with-a-custom-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!