asp.net中的TDD新手,我是否在正确的轨道上编写测试?
发布时间:2020-12-16 07:02:41 所属栏目:asp.Net 来源:网络整理
导读:在过去的几个月里,我一直在阅读有关TDD的很多内容,并决定试着用一个简单的例子来试一试,我只是不确定我是否在实践中测试正确的东西.这里是用于验证电子邮件的自定义数据注释的测试: using System;using System.Text;using System.Collections.Generic;using
在过去的几个月里,我一直在阅读有关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("john.smith@example.com"); // 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; } } 所有测试最初都失败了,然后在编写代码后成功,但测试是否写得恰当?太多或太少?我知道这是一个非常简单的例子,但我想确保自己走上正确的轨道,然后才能开始更复杂的事情. 解决方法
我认为你走在正确的轨道上.在这一点上,我建议你在测试中进行一些重构.因为你正在使用
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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 如何在ASP.NET中为不同的URL设置不同的超时
- asp.net-mvc – 如何在VS2012 MVC4项目中设置Ext
- asp.net-mvc – MapMvcAttributeRoutes:此方法不
- asp.net-mvc – ASP.NET MVC2的性能监控?
- ASP.NET找到了具有相同ID“x”的多个控件.的Find
- entity-framework – 数据读取器与指定的模型不兼
- entity-framework – WithOptional with Entity
- asp.net-mvc-3 – .NET MVC 3自定义十进制?模型
- asp.net – App_Start文件夹在ASP 4.5仅在WebApp
- asp.net-mvc – ASP.NET MVC5/IIS Express无法调
热点阅读