2012-04-23 23 views
0

我有发送电子邮件的简单方法:一个方法应该抛出一个例外的单元测试?

public void notifyEmail(string messageSubject, string messageBody) 
{ 
    MailMessage message = new MailMessage(from, to); 

    message.Subject = messageSubject; 
    message.Body = messageBody; 

    SmtpClient client = new SmtpClient(smtp_client); 
    client.Send(message); 

    message.Dispose();//release everything related 
} 

以及单元测试(我学习):

[TestMethod()] 
    public void notifyEmailTest() 
    { 
     eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value 

     bool testSent = true; 
     try 
     { 
      target.notifyEmail(); 
     } 
     catch (Exception) 
     { 
      testSent = false; 
     } 

     Assert.IsTrue(testSent);    
    } 

我特意设置的smtp_client变量值的东西无效。

在我的项目中运行代码会导致错误。

运行测试方法会导致Pass。我的测试或方法应该采用不同的结构,以便测试失败?

+2

你肯定需要重构你的测试。你是否想要重构你的代码取决于你是否想让它更易于测试。 – Bernard 2012-04-23 19:03:17

回答

2

我总是尽我所能,以避免使在我的单元测试中使用try-catch子句。相反,尝试使用的ExpectedException属性(属性是NUnit的和MSTest的相同),并设置类型异常你期望即

[TestMethod] 
[ExpectedException(typeof(NetworkException))] 
public void ShouldThrowNetworkExceptionIfSmtpServerIsInvalid) 
{ 
    //... test code here. 
} 

,我已经使用的另一种方法是创建一个静态类与AssertExpectedException方法,因为有时一个方法可能因为不同的原因而抛出相同类型的异常,并且唯一能够确定是否返回准确的消息的方法是使用自定义代码,因为该属性不会断言抛出的异常返回的消息。

希望这会有所帮助。

问候。

2

如果你期望target.notifyEmail()应该抛出异常,那么这就是你应该测试的。如果您使用NUnit,则可以使用Assert.Throws<T>,例如

[Test] 
public void notifyEmailTestFails() 
{ 
    // TODO: Initialize to an appropriate value 
    eMail target = new eMail("TEST Subject","TEST Body"); 
    Assert.Throws<InvalidOperationException>(target.notifyEmail()); 
} 

不过,现在我看到你正在使用VSUnit你应该使用[ExpectedException(typeof(...))] 在其他的答案中提到。

一般而言,您应该针对成功,失败和异常情况分别进行测试。

+1

我不认为MSTest Assert类有这个。与NUnit的版本相比,它非常缺乏。 – aquinas 2012-04-23 19:08:45

+1

你说得对。我没有看标签:( – Phil 2012-04-23 19:10:32

1

的方式,我通常这样做是ExpectedExceptionhttp://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute(v=vs.80).aspx)来装点测试

。但是你想要捕捉比“例外”更少的通用性。

如果你不想使用预期的异常,然后取代:

bool testSent = true; 

     try 
     { 
      target.notifyEmail(); 
     } 
     catch (Exception) 
     { 
      testSent = false; 
     } 

     Assert.IsTrue(testSent); 

你可以少一些冗长:

try{ 
target.notifyEmail(); 
Assert.Fail("Expected an exception here"); 
} 
catch (SmtpException){ 

} 
0

我会强烈建议您尝试FluenAssertions:

http://fluentassertions.codeplex.com/

他们是简单真棒,优雅

,他们让你检查异常消息(你不能做到这一点与ExpectedException属性)

示例:

using FluentAssertions; 

[TestMethod] 
public void notifyEmailTest() 
{ 
    eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value 

target.Invoking(x => x.notifyEmail()) 
    .ShouldThrow<YourExcpectedException>() 
      .WithMessage("Your expected message", FluentAssertions.Assertions.ComparisonMode.Substring); 
} 
相关问题