【问题标题】:NUnit - Getter Setter Method TestingNUnit - Getter Setter 方法测试
【发布时间】:2015-06-25 22:49:17
【问题描述】:

我正在尝试如下测试 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

谁能告诉我,我做错了什么?

【问题讨论】:

  • StackFrame() 方法(它的 C'tor)是否有任何属性?似乎测试在这一行失败:Assert.AreEqual(1, customAttributes.Count());
  • @OldFox StackFrame() 初始化 System.Diagnostics.StackFrame 类的新实例,这是否回答了您的问题?您认为这是测试 Getter Setter 方法的正确方法吗??
  • 是的,它回答了我的问题。您的测试失败,因为 StackFrame 的 C''tor 没有属性。您要在测试中验证什么行为?
  • @OldFox 我基本上是在尝试测试该方法是否可以读取/写入/存储信息。这有意义吗?
  • 最简单的解决方案也是如此。将数据放入属性中,然后对属性执行断言。

标签: c# asp.net .net unit-testing nunit


【解决方案1】:

您尝试验证的行为是“我可以从我的类属性中读取和写入数据”。实现此行为的最简单方法是:

[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(更改方法签名)

【讨论】:

  • 我100%支持你,但是,我想知道,如果我将签名更改为PropertyInfo,我该如何更改TestHelperGetterSetter&lt;GetToken, object&gt;(new StackFrame().GetMethod(), "TokenKey", 77);??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 2017-09-09
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多