我正在尝试测试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
有人能告诉我,我做错了什么?
答案 0 :(得分:3)
您要验证的行为是&#34;我可以从我的类属性读取和写入数据&#34;。实现此行为的最简单方法是:
[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
(更改方法签名)