【发布时间】: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