在過去的幾個月裏,我一直在閱讀很多關於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;
}
}
所有的測試最初失敗,然後編寫代碼後成功,但測試是否適當寫入?太多,還是太少?我知道這是一個非常簡單的例子,但我想確保在走向更復雜的事情之前我走在正確的軌道上。
也許完全是offtopic,但我會說它無論如何:轉儲VS集成測試的東西,並取而代之的是NUnit。就像MSBuild vs NAnt一樣,VSTS並沒有提供你在NUnit中找到的廣泛的功能和靈活性。 除此之外,我認爲你正在接近這一點。 – kprobst 2010-08-09 17:55:08
這確實是完全不合時宜的:)我認爲這是個人喜好的問題。我使用Visual Studio測試工具,它們對我來說工作得非常好,都集成在VS中。 – Cocowalla 2010-08-09 18:01:39
@Coco:他們也很好地融入TFS。 – 2010-08-09 18:32:16