我创建了一个类库.
我已经创建了单元测试项目来对单元进行单元测试.
我经历了一个特殊的课程
" ExpectedExceptionAttribute Class "
我试图实现它.但是,如果我启用该属性,我的代码始终显示失败.即使数据是正确的.
课程:
public class SampleTestClass
{
public double CheckValidAmount(object Name , double amount)
{
try
{
if (amount == 1.0 && Name.ToString() == "RamKumar")
return 10.0 - amount;
else
return amount;
}
catch (NullReferenceException ex)
{
return amount;
}
}
}
单元测试通行证:
[TestClass]
public class SampleTester
{
[TestMethod]
public void CheckValidAmount()
{
SampleTestClass sp = new SampleTestClass();
double dd = sp.CheckValidAmount("RamKumar", 1.0);
Assert.AreEqual(dd, 9.0);
}
}
失败:
[TestClass]
public class SampleTester
{
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void CheckValidAmount()
{
SampleTestClass sp = new SampleTestClass();
double dd = sp.CheckValidAmount(null, 1.0); // here i have mentioned NULL
Assert.AreEqual(dd, 9.0);
}
}
预计将通过:
[TestClass]
public class SampleTester
{
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void CheckValidAmount()
{
SampleTestClass sp = new SampleTestClass();
double dd = sp.CheckValidAmount("RamKumar", 1.0);
Assert.AreEqual(dd, 9.0);
}
}
最后一个应该通过..但它总是显示失败…
参考:
ExpectedExceptionAttribute Class :
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx
我的VS显示了这条消息:
![enter image description here][1]
请指导我理解这一点..谢谢
http://i.stack./G2R1b.png 解决方法: 如果要验证方法是否抛出了正确的异常,则应使用ExpectedExceptionAttribute.在您的情况下,您不会抛出任何异常(从您的方法).您的方法行为是:
给定金额为1.0
当我用无效名称检查金额时(NULL名称)
然后我应该得到1.0金额
从我的GWT可以看出,你的方法行为不会引发任何异常.因此您的测试失败了.
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]// remove this attribute to pass the test
public void CheckValidAmount()
{
SampleTestClass sp = new SampleTestClass();
double dd = sp.CheckValidAmount("RamKumar", 1.0);
Assert.AreEqual(dd, 9.0);
}
当方法行为类似于:时,应使用ExpectedExceptionAttribute:
给定金额为1.0
当我用无效名称检查金额时(NULL名称)
然后应该引发ArgumentNullException
在这种情况下,您的方法是:
public double CheckValidAmount(object Name, double amount)
{
if (Name == null)
throw new ArgumentNullException("Name");
if (amount == 1.0 && Name.ToString() == "RamKumar")
return 10.0 - amount;
return amount;
}
你的测试方法应该是:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CheckValidAmount_CallWithInvalidName_Throw()
{
SampleTestClass sp = new SampleTestClass();
sp.CheckValidAmount("RamKumar", 1.0);
}
来源:http://www./content-1-233651.html
|