NUnit - Getter Setter 方法测试

NUnit - Getter Setter Method Testing

我正在尝试如下测试 getter 和 setter 方法

  public class GetToken
     {
         public string TokenStatusCode { get; set; }
         public AccountPrimary TokenKey { get; set; }
     }

NUnit代码如下

    [Test]
    public void GetToken_StatusCode()
    {
        TestHelperGetterSetter<GetToken, string>(new StackFrame().GetMethod(), 
        "TokenStatusCode", "RipSnorter");
    }

    [Test]
    public void GetToken_TokenIden()
    {
        TestHelperGetterSetter<GetToken, object>(new StackFrame().GetMethod(),
        "TokenKey", 77);
    }

有帮手如下

  private void TestHelperGetterSetter<TAttr, TProp>(MethodBase method,
                 string argName, TProp expectedValue)
    {
        object[] customAttributes = method.GetCustomAttributes(typeof(TAttr), false);

        Assert.AreEqual(1, customAttributes.Count());

        TAttr attr = (TAttr)customAttributes[0];

        PropertyInfo propertyInfo = attr.GetType().GetProperty(argName);

        Assert.IsNotNull(propertyInfo);
        Assert.AreEqual(typeof(TProp), propertyInfo.PropertyType);
        Assert.IsTrue(propertyInfo.CanRead);
        Assert.IsTrue(propertyInfo.CanWrite);
        Assert.AreEqual(expectedValue, (TProp)propertyInfo.GetValue(attr, null));
    }

每次我 运行 测试都会失败,结果如下

 Expected: 1
 But was:  0

有人可以告诉我,我做错了什么吗?

您要验证的行为是 "I can read and write data from my class properties"。实现此行为的最简单方法是:

[setup]
public void testInit()
{
     target = new GetToken();
}

[Test]
public void GetToken_StatusCode()
{
    var expectedValue = "RipSnorter";
    target.TokenStatusCode = expectedValue;
    Assert.AreEquals(expectedValue, target.TokenStatusCode);
}

做同样的事情 TokenKey ....

如果您仍想使用您的方法,则需要删除:

    object[] customAttributes = method.GetCustomAttributes(typeof(TAttr), false);
    Assert.AreEqual(1, customAttributes.Count());
    TAttr attr = (TAttr)customAttributes[0];
    PropertyInfo propertyInfo = attr.GetType().GetProperty(argName);

然后传递PropertyInfo而不是MethodBase(更改方法签名)