我正在閱讀Asp.net MVC框架,我正在閱讀有關IDataErrorInfo作爲驗證的形式。如何對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。
那麼我會如何測試這個?我喜歡檢查錯誤信息,看看它們是否相同。就像我傳入一個空字段一樣,我想檢查錯誤消息是否是該空字段的正確字段。
之後我喜歡檢查是否需要驗證的東西之後的語句邏輯,看看它是否在做預期的工作,但我甚至不知道如何調用這個部分類,尤其是因爲您通常不會希望在進行單元測試時碰到數據庫。
您發佈的商品類是部分商品。必須有一個或多個Product類的其他實現(除其他外)調用部分方法。當我們不知道什麼樣子時,回答你的問題並不容易。另外,我沒有看到Repository和Controller與這個有什麼關係,所以也許你可以減少你的問題? – 2009-08-21 07:10:42