2011-08-23 72 views
1

asp.net写单元测试我有一个Repositry类至极发起这样的:返回异常

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); 
    } 
} 

我的问题是:这是正确的方式,这样做呢?我在解决此问题方面遇到问题。

回答

0

我喜欢GarethOwen的答案(的的ExpectedException属性)或这样:

public void MyTest() 
{ 
    try 
    {  
     target = new ContactRepository("kvelland-kk", sqlStr); 

     Assert.Fail("Should have failed with MyExceptionType"); 
    } 
    catch(MyExceptionType){} 
} 

检查异常消息不是一个好主意。因为您可能会根据系统本地化获得不同的消息。改为检查异常类型。正如Xhalent所提到的,不要抛出异常,抛出特定类型的异常。

0

您忘记抛出新的异常

新的异常(“没有SQL字符串定义”);

有趣的是,这种证明了单元测试的价值,因为它们在查找时显示出一个简单的编码错误。

3

我宁愿使用的ExpectedException属性来标记您的TestMethod的,并抛出一个更具体的异常类型,例如一个ArgumentException:

[TestMethod()] 
[ExpectedException(typeof(System.ArgumentException))] 
public void CreateContactRepositoryWithEmtySqlString() 
{ 
    ContactRepository target = new ContactRepository("kvelland-kk", string.Empty); 
} 
+1

除非你期望的异常是一个专门的派生异常,否则捕捉任何异常对于任何形式的行为都是开放的,所以很难知道你是否抛出了你期望的确切异常。 – Xhalent

+0

重要的一点Xhalent - 我更新了我的答案,期望得到'ArgumentException'而不是'Exception' – GarethOwen