2017-06-15 32 views
0

我目前正在測試一個Active Directory獲取Active Directory中的用戶的方法。當我作爲參數傳遞的字符串使用非法字符時,我的測試方法應該查找拋出的異常。這裏是我的測試方法:ArgumentException不拋出C#測試

public List<ADProperties> SearchUserByName(string name) 
{ 
    try 
    { 
     //Active Directory properties loading here 
     if(condition) 
     { 
      //Condition throws ArgumentException because of invalid AD Filter using characters 
      return null; 
     } 
    } 
    catch(ArgumentException ae) 
    { 
     Console.WriteLine("AE caught : "+ae.ToString()); 
    } 
} 

我應該精確的是,當異常發生在這個精確點打斷了我的程序就行了。 這裏是我的測試方法:

[TestMethod] 
[ExpectedException(typeof(ArgumentException))] 
public void SearchUserByNameIllegalCharsTest() 
{ 
    string generateChars = new string('*', 10); 
    List<ADProperties> test3 = adManager.SearchUserByName(generateChars); 
    //ArgumentException is thrown on this call 
} 

即使ArgumentException被拋出,我的測試還是失敗了,說方法沒有拋出預期的異常。我在這裏沒有看到什麼? 感謝您的幫助。

+0

因爲你捉內'SearchUserByName',測試方法毫不知情的例外呢? –

回答

1

你不拋出異常的任何地方。使用catch語句,沒有任何內容告訴外部塊或範圍發生異常。您可以在Console.WriteLine

public List<ADProperties> SearchUserByName(string name) 
{ 
    try 
    { 
     //Active Directory properties loading here 
     if(condition) 
     { 
      //Condition throws ArgumentException because of invalid AD Filter using characters 
      return null; 
     } 
    } 
    catch(ArgumentException ae) 
    { 
     Console.WriteLine("AE caught : "+ae.ToString()); 
     throw ae; 
    } 
} 

後添加投擲或刪除try-catch塊

public List<ADProperties> SearchUserByName(string name) 
{ 
     //Active Directory properties loading here 
     if(condition) 
     { 
      //Condition throws ArgumentException because of invalid AD Filter using characters 
      return null; 
     } 
} 
+0

好的,謝謝你! –

2

請注意,您的方法捕捉異常而不會重新拋出它。爲了能夠看到異常在單元測試中,你應該有一個語句進行捕捉:

try { 
     //Active Directory properties loading here 
     if(condition){ //Condition throws ArgumentException because of invalid AD Filter using characters 
      return null; 
     } 
    }catch(ArgumentException ae){ 
     Console.WriteLine("AE caught : "+ae.ToString()); 
     throw; 
    } 
+0

或者你根本不需要知道它,測試框架應該記錄它。 –

+0

@RobinSalih因爲在這種情況下,它是一個未經檢查的異常? –

相關問題