NUnit-Getter Setter方法测试
本文关键字:测试 方法 Setter NUnit-Getter | 更新日期: 2023-09-27 18:00:01
我正在尝试测试一个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
有人能告诉我,我做错了什么吗?
您试图验证的行为是"我可以从类属性中读取和写入数据"。实现这种行为的最简单方法是:
[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
(更改方法签名)