I'm currently testing an Active Directory
Method that fetches users in Active Directory. My test method is supposed to look for an exception thrown when the string I pass as argument is using illegal characters. Here is my tested method:
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());
}
}
I should precise that the line where the exception occurs interrupts my program at this precise point. Here is my test method:
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SearchUserByNameIllegalCharsTest()
{
string generateChars = new string('*', 10);
List<ADProperties> test3 = adManager.SearchUserByName(generateChars);
//ArgumentException is thrown on this call
}
Even though the ArgumentException
is thrown, my test still failed, saying the method has not thrown the expected Exception. What am I not seeing here?
Thanks for your help.
答案 0 :(得分:1)
Note that your method is catching the exception without re-throwing it. To be able to see the exception in the Unit Test you should have a throw statement in your catch:
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;
}
答案 1 :(得分: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;
}
}