>假设您有一个函数来检查提供的字符串值是否为空,如下所示:
string IsNotEmpty(string value)
{
if (!string.IsEmpty(value)) return value
else throw new Exception("Value is empty");
}
另外,假设我们的代码中有许多其他部分调用此泛型函数来检查是否存在值,如果没有,则抛出比泛型函数更具体的异常。作为示例,我将提供以下代码:
string CheckEmail(string email)
{
try
{
return IsNotEmpty(email);
}
catch(Exception ex)
{
throw new **EmptyEmailException**("Please provide your email");
}
}
现在我想为 CheckEmail 函数编写一个 MSTest,该函数期望抛出EmptyEmailException类型的异常。但不幸的是,该测试仅捕获来自 IsNotEmpty 函数的通用异常,它会停止执行,并且代码永远不会测试第二个异常。
我做过的事情没有任何成功:
- 我使用 ExpectException 属性编写了测试。
- 我写了我的测试 与 Assert.ThrowsException.
- 我更新了VS中的异常设置 不要在异常类型的异常上刹车,只是为了看看是否 将解决我的问题。
无论我做什么,MSTest总是报告第一个异常,当然我的测试失败了。以下是我当前的测试代码:
[TestMethod]
public void When_Validating_SignInRequest_And_Email_IsEmpty_Raise_EmptyEmailException()
{
var ex = Assert.ThrowsException<EmptyEmailException>(
() => CheckEmail(string.Empty)
);
}
谁能指出我正确的方向?
谢谢。
这对我来说效果很好:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace MyNamespace
{
public class EmptyEmailException : Exception
{
public EmptyEmailException(string message) : base(message)
{ }
}
public class MyClass
{
public static string IsNotEmpty(string value)
{
if (!string.IsNullOrEmpty(value))
return value;
else
throw new Exception("Value is empty");
}
public static string CheckEmail(string email)
{
try
{
return IsNotEmpty(email);
}
catch
{
throw new EmptyEmailException("Please provide your email");
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.ThrowsException<EmptyEmailException>(() => MyClass.CheckEmail(string.Empty));
}
}
}