返回异常的asp.net写单元测试
我有一个寄存班,里面有这样的同修:返回异常的asp.net写单元测试,asp.net,unit-testing,Asp.net,Unit Testing,我有一个寄存班,里面有这样的同修: public ContactRepository(string sqlStr, string username) { if (!string.IsNullOrEmpty(sqlStr)) { ent = new AceoEntities(sqlStr); Username = username; } else new Exception("No sql string is def
public ContactRepository(string sqlStr, string username)
{
if (!string.IsNullOrEmpty(sqlStr))
{
ent = new AceoEntities(sqlStr);
Username = username;
}
else
new Exception("No sql string is defined");
}
这可能不是最好的方法,但我想确保在没有sqlStr的情况下不可能在类外创建实例
然后我试着测试这个:
[TestMethod()]
public void CreateContactRepositoryWithEmtySqlString()
{
string sqlStr = string.Empty;
ContactRepository target;
try
{
target = new ContactRepository("kvelland-kk", sqlStr);
}
catch (Exception e)
{
Assert.AreEqual("No sql string is defined",e.Message);
}
}
我的问题是:这是正确的方法吗?我无法使其正常工作。您忘记了抛出新异常 抛出新异常(“未定义sql字符串”)
有趣的是,这类代码演示了单元测试的价值,因为它们显示了一个容易忽略的简单编码错误。我宁愿使用ExpectedException属性来标记您的TestMethod,并抛出一种更具体的异常类型,例如ArgumentException:
[TestMethod()]
[ExpectedException(typeof(System.ArgumentException))]
public void CreateContactRepositoryWithEmtySqlString()
{
ContactRepository target = new ContactRepository("kvelland-kk", string.Empty);
}
我更喜欢Garetohen的答案(ExpectedException属性)或者这样:
public void MyTest()
{
try
{
target = new ContactRepository("kvelland-kk", sqlStr);
Assert.Fail("Should have failed with MyExceptionType");
}
catch(MyExceptionType){}
}
检查异常消息不是一个好主意。因为您可能会收到基于系统本地化的不同消息。改为检查异常类型。正如Xhalent提到的,不要抛出异常,而是抛出特定类型的异常 除非您期望的异常是一个专门的派生异常,否则捕获“any”异常对任何类型的行为都有点开放,所以它是;很难知道您是否抛出了预期的异常。要点Xhalent-我更新了我的答案,希望出现“ArgumentException”,而不是“exception”