如何对 IDataErrorInfo 进行单元测试?

发布于 2024-08-02 16:27:18 字数 3208 浏览 4 评论 0原文

我正在阅读 Asp.net MVC Framework,并且正在阅读有关 IDataErrorInfo 作为验证形式的内容。

所以我只想发布他所拥有的内容。

产品类

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace MvcApplication1.Models
{
    public partial class Product : IDataErrorInfo
    {

        private Dictionary<string, string> _errors = new Dictionary<string, string>();

        partial void OnNameChanging(string value)
        {
            if (value.Trim() == String.Empty)
                _errors.Add("Name", "Name is required.");
        }


        partial void OnPriceChanging(decimal value)
        {
            if (value <= 0m)
                _errors.Add("Price", "Price must be greater than 0.");
        }


        #region IDataErrorInfo Members

        public string Error
        {
            get { return string.Empty; }
        }

        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                    return _errors[columnName];
                return string.Empty;
            }
        }

        #endregion


    }
}

ProductRepository。

using System.Collections.Generic;
using System.Linq;

namespace MvcApplication1.Models
{
    public class ProductRepository : IProductRepository
    {
        private ProductsDBEntities _entities = new ProductsDBEntities();

        public IEnumerable<Product> ListProducts()
        {
            return _entities.ProductSet.ToList();
        }

        public void CreateProduct(Product productToCreate)
        {
            _entities.AddToProductSet(productToCreate);
            _entities.SaveChanges();
        }

    }

    public interface IProductRepository
    {
        IEnumerable<Product> ListProducts();
        void CreateProduct(Product productToCreate);
    }
}

控制器

using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class ProductController : Controller
    {
        private IProductRepository _repository; 

        public ProductController()
            :this(new ProductRepository()){}


        public ProductController(IProductRepository repository)
        {
            _repository = repository;
        }


        public ActionResult Index()
        {
            return View(_repository.ListProducts());
        }


        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Product/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude="Id")]Product productToCreate)
        {
            if (!ModelState.IsValid)
                return View();
            _repository.CreateProduct(productToCreate);
            return RedirectToAction("Index");
        }


    }
}

然而,我在书中没有看到如何实际对其进行单元测试。就像他向您展示了如何对他的服务层内容进行单元测试,但没有介绍有关单元测试 IDataErrorInfo 的内容。

那么我该如何进行单元测试呢?我喜欢检查错误消息以查看它们是否相同。就像我传入一个空字段一样,我想检查错误消息是否是该空字段的正确消息。

在我喜欢在需要验证的内容之后检查 if 语句逻辑,以查看它是否正在执行预期的操作,但我什至不知道如何调用这个部分类,特别是因为您通常不想点击进行单元测试时使用数据库。

I am reading Asp.net MVC Framework and I am reading about IDataErrorInfo as form of validation.

So I am just going to post what he has.

Product Class

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace MvcApplication1.Models
{
    public partial class Product : IDataErrorInfo
    {

        private Dictionary<string, string> _errors = new Dictionary<string, string>();

        partial void OnNameChanging(string value)
        {
            if (value.Trim() == String.Empty)
                _errors.Add("Name", "Name is required.");
        }


        partial void OnPriceChanging(decimal value)
        {
            if (value <= 0m)
                _errors.Add("Price", "Price must be greater than 0.");
        }


        #region IDataErrorInfo Members

        public string Error
        {
            get { return string.Empty; }
        }

        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                    return _errors[columnName];
                return string.Empty;
            }
        }

        #endregion


    }
}

ProductRepository.

using System.Collections.Generic;
using System.Linq;

namespace MvcApplication1.Models
{
    public class ProductRepository : IProductRepository
    {
        private ProductsDBEntities _entities = new ProductsDBEntities();

        public IEnumerable<Product> ListProducts()
        {
            return _entities.ProductSet.ToList();
        }

        public void CreateProduct(Product productToCreate)
        {
            _entities.AddToProductSet(productToCreate);
            _entities.SaveChanges();
        }

    }

    public interface IProductRepository
    {
        IEnumerable<Product> ListProducts();
        void CreateProduct(Product productToCreate);
    }
}

Controller

using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class ProductController : Controller
    {
        private IProductRepository _repository; 

        public ProductController()
            :this(new ProductRepository()){}


        public ProductController(IProductRepository repository)
        {
            _repository = repository;
        }


        public ActionResult Index()
        {
            return View(_repository.ListProducts());
        }


        //
        // GET: /Product/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Product/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind(Exclude="Id")]Product productToCreate)
        {
            if (!ModelState.IsValid)
                return View();
            _repository.CreateProduct(productToCreate);
            return RedirectToAction("Index");
        }


    }
}

Yet No where in the book do I see how to actually unit test this. Like he shows you how to unit test his service layer stuff but nothing about unit testing IDataErrorInfo.

So how would I unit test this? I like checking the error messages to see if they are the same. Like if I pass in a null field I like to check if the error message would be the right one for this null field.

After I like to check if statement logic after the stuff that needs to be validated to see if it is doing what is expected but I don't even know how to call this partial class up especially since you normally don't want to hit the database when doing unit tests.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野生奥特曼 2024-08-09 16:27:18

马特提到的解决方案仅适用于我,如果我使用后面的语句来断言 -

Assert.AreEqual("Name is required.", _product["Name"]); - 这对我有用

Assert.AreEqual("Name is required.", _product.Error); - 这对我不起作用

The solution mentioned by Matt only works for me if i use the later statement to Assert -

Assert.AreEqual("Name is required.", _product["Name"]); - this works for me

Assert.AreEqual("Name is required.", _product.Error); - this doesn't work for me

你另情深 2024-08-09 16:27:18

单元测试 IDataErrorInfo 非常简单。只需使用对象的“有效”实例设置测试,然后测试是否可以使其出错:

[TestFixture]
public class ErrorTests
{
    private Product _product; // subject under test

    [SetUp]
    public void Create_valid_instance()
    {
        _product = new Product { /* valid values */ };
    }

    [Test]
    public void Name_cannot_be_null()
    {
        _product.Name = null; 
        Assert.AreEqual("Name is required.", _product.Error);
        Assert.AreEqual("Name is required.", _product["Name"]);
    }

    [Test]
    public void Name_cannot_be_empty()
    {
        _product.Name = String.Empty; 
        Assert.AreEqual("Name is required.", _product.Error);
        Assert.AreEqual("Name is required.", _product["Name"]);
    }

    [Test]
    public void Name_cannot_be_whitespace()
    {
        _product.Name = "   ";
        Assert.AreEqual("Name is required.", _product.Error);
        Assert.AreEqual("Name is required.", _product["Name"]);
    }

    /* etc - add tests to prove that errors can occur */
}

Unit testing IDataErrorInfo is quite easy. Just set up your tests with a "valid" instance of the object, then test that you can make it error:

[TestFixture]
public class ErrorTests
{
    private Product _product; // subject under test

    [SetUp]
    public void Create_valid_instance()
    {
        _product = new Product { /* valid values */ };
    }

    [Test]
    public void Name_cannot_be_null()
    {
        _product.Name = null; 
        Assert.AreEqual("Name is required.", _product.Error);
        Assert.AreEqual("Name is required.", _product["Name"]);
    }

    [Test]
    public void Name_cannot_be_empty()
    {
        _product.Name = String.Empty; 
        Assert.AreEqual("Name is required.", _product.Error);
        Assert.AreEqual("Name is required.", _product["Name"]);
    }

    [Test]
    public void Name_cannot_be_whitespace()
    {
        _product.Name = "   ";
        Assert.AreEqual("Name is required.", _product.Error);
        Assert.AreEqual("Name is required.", _product["Name"]);
    }

    /* etc - add tests to prove that errors can occur */
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文