我已经创建了一个类库。
我已经创建了单元测试项目来对一个类进行单元测试。
我上过一门特殊的课
" 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);
}
}
最后一个应该pass了..但是总是显示Failed...
引用:
ExpectedExceptionAttribute Class :
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx
我的 VS 显示此消息:
![enter image description here][1]
请指导我理解这一点..谢谢
最佳答案
当您想要验证您的方法是否抛出正确的异常时,您应该使用 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);
}
关于c# - ExpectedException 属性无法显示预期结果 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092611/