2010-08-09 39 views
5

在過去的幾個月裏,我一直在閱讀很多關於TDD的文章,並且決定嘗試一個簡單的例子,我只是不確定我是否在實踐中測試了正確的東西。這裏自定義數據註解測試用於驗證電子郵件:在asp.NET中對於TDD來說是新手,我在正確的軌道上編寫測試嗎?

using System; 
using System.Text; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 

namespace MembershipTest.Tests 
{ 
    [TestClass] 
    public class CustomDataAnnotationsTest 
    { 
     [TestMethod] 
     public void CustomDataAnnotations_Email_ReturnTrueIfNull() 
     { 
      // Arrange 
      EmailAttribute attribute = new EmailAttribute(); 

      // Act 
      bool result = attribute.IsValid(null); 

      // Assert 
      Assert.AreEqual(true, result); 
     } 

     [TestMethod] 
     public void CustomDataAnnotations_Email_ReturnFalseIfInvalid() 
     { 
      // Arrange 
      EmailAttribute attribute = new EmailAttribute(); 

      // Act 
      bool result = attribute.IsValid("()[]\\;:,<>@example.com"); 

      // Assert 
      Assert.AreEqual(false, result); 
     } 

     [TestMethod] 
     public void CustomDataAnnotations_Email_ReturnTrueIfValid() 
     { 
      // Arrange 
      EmailAttribute attribute = new EmailAttribute(); 

      // Act 
      bool result = attribute.IsValid("[email protected]"); 

      // Assert 
      Assert.AreEqual(true, result); 
     } 
    } 
} 

這裏是後續代碼的測試寫着:

using System; 
using System.ComponentModel.DataAnnotations; 
using System.Net.Mail; 

public class EmailAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     //Let RequiredAttribute validate whether the value is required or not. 
     if (value == null) 
     { 
      return true; 
     } 

     //Check to see if System.Net.Mail can send to the address. 
     try 
     { 
      var i = new MailAddress(value.ToString()); 
     } 
     catch (Exception) 
     { 
      return false; 
     } 

     return true; 
    } 

} 

所有的測試最初失敗,然後編寫代碼後成功,但測試是否適當寫入?太多,還是太少?我知道這是一個非常簡單的例子,但我想確保在走向更復雜的事情之前我走在正確的軌道上。

+0

也許完全是offtopic,但我會說它無論如何:轉儲VS集成測試的東西,並取而代之的是NUnit。就像MSBuild vs NAnt一樣,VSTS並沒有提供你在NUnit中找到的廣泛的功能和靈活性。 除此之外,我認爲你正在接近這一點。 – kprobst 2010-08-09 17:55:08

+5

這確實是完全不合時宜的:)我認爲這是個人喜好的問題。我使用Visual Studio測試工具,它們對我來說工作得非常好,都集成在VS中。 – Cocowalla 2010-08-09 18:01:39

+1

@Coco:他們也很好地融入TFS。 – 2010-08-09 18:32:16

回答

6

我認爲你是在正確的軌道上。在這一點上,我會建議在你的測試中進行一些重構。由於您在每次測試中都使用

EmailAttribute attribute = new EmailAttribute(); 

。我會建議創建TestInitialize()和TestCleanup()方法。 TestInitialize會新建EmailAttribute並且TestCleanup會將對象清空。這只是一個偏好問題。像這樣

private EmailAttribute _attribute; 

[TestInitialize] 
public void TestInitialize() 
{ 
    _attribute = new EmailAttribute 
} 

[TestCleanup] 
public void TestCleanup() 
{ 
    _attribute = null; 
} 
+0

這裏有一個很棒的地方,使用SetUp/TearDown是一個很好的練習:) – wintermute 2010-08-09 17:44:25

+3

您的觀點非常有效,但是使用Visual Studio單元測試工具,我認爲這些屬性應該分別是TestInitialize和TestCleanup你使用的是NUnit):D – Cocowalla 2010-08-09 17:47:18

+0

謝謝Cocowalla。我更改了屬性名稱。 – mpenrow 2010-08-09 17:49:17

相關問題