1

我正在尝试研究单元测试最佳实践,但遇到了一个我无法理解的问题。生产代码具有将给定对象转换为另一个对象的函数,如下所示:

原始对象:

public OriginalObject
{
    public string Id {get; set;}
    public string Value {get; set;}
    public int FormCode {get; set;}
    public int NameCode {get; set;}
    //other properties
}

public TransformedObject
{
    public string Value {get; set;}
    public int FormCode {get; set;}
    //other properties
}

变换功能:

public TransformedObject Transform(OriginalObject originalObject)
{
    var TransformedObject = new TransformedObject();
    TransformedObject.Value = originalObject.Value;
    TransformedObject.FormCode = originalObject.FormCode;
    return TransformedObject;
}

测试看起来像这样:

[Test]
public void Transform_NonNullOptionObject_ValuePropertyIsTheSame()
{
    OptionObjectTransform transform = InitTransform();
    CustomOptionObject result = transform.Transform(optionObject);//mock optionObject
    Assert.AreEqual(optionObject.Value, result.Value);
}

所以我的问题是我必须为每个属性编写一个测试吗?或者有没有办法使用[TestCase]传递我要测试的属性?或者测试是否应该检查所有属性是否相等?我不认为最后一个是解决方案,因为如果测试失败,那么我们将不知道哪些属性不匹配。

4

2 回答 2

0

A limitation of NUnit (and all other xUnit frameworks) is that they fail on the first assert failure and do not run the other asserts. As you say, this means that if one tries to test many values, through many asserts, there's no way to detect multiple failures.

However, as you also identify, many repeated tests, each of which tests a different value isn't ideal either as it involves lots of duplicated code, just to work around a limitation of NUnit.

The "best of both worlds" solution is to test arrays of objects for equality. This could take the form of:

[Test]
public void Transform_NonNullOptionObject_ValuePropertyIsTheSame()
{
    OptionObjectTransform transform = InitTransform();
    CustomOptionObject result = transform.Transform(optionObject);
    var expected = new[] { optionObject.Value, optionObject.FormCode };
    var actual = new[] { result.Value, result.FormCode };
    Assert.AreEqual(expected, actual);
}

That way, you test many values with one test and can know about many failures simultaneously.

于 2013-10-25T15:50:30.600 回答
0

对于简单的映射(即计算映射很少或“如果”),我使用SharpTestEx,其中有一个不错的Satisfyassertion,它报告所有错误的断言。

代码如下:

mapped.Satisfy( m =>
    m.Prop1 == source.SomeData + "zz" &&
    m.Prop2 == source.Prop2 ...
);
于 2013-10-25T19:32:20.580 回答