문제

ASP.NET MVC 프레임 워크를 읽고 있으며 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


    }
}

생산 분해.

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 장치 테스트에 대해서는 아무것도 없습니다.

그렇다면 어떻게 이것을 테스트 할 것인가? 오류 메시지를 확인하여 동일인지 확인하는 것이 좋습니다. 널 필드를 통과하는 것처럼 오류 메시지 가이 널 필드에 적합한 지 확인하고 싶습니다.

내가 예상되는 일을하고 있는지 확인하기 위해 검증해야 할 사항을 확인한 후 명령문 논리를 확인한 후에는 일반적 으로이 부분 클래스를 호출하는 방법조차 모르겠습니다. 단위 테스트를 수행 할 때 데이터베이스.

도움이 되었습니까?

해결책

단위 테스트 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 */
}

다른 팁

Matt가 언급 한 솔루션은 나중에 진술을 사용하여 Assert-

assert.areequal ( "이름이 필요합니다.", _product [ "name"]); - 이것은 나를 위해 작동합니다

Assert.areequal ( "이름이 필요합니다.", _product.error); - 이것은 나에게는 효과가 없습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top