2009-08-21 2 views
-1

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에 대해서는 전혀 설명하지 않습니다.

어떻게 단위 테스트를할까요? 나는 그들이 같은지보기 위해 오류 메시지를 확인하는 것을 좋아한다. 마치 null 필드에 전달하는 경우 오류 메시지가이 null 필드에 적합한 것인지 확인하고 싶습니다.

예상치 못한 일을하고 있는지 확인해야하는 내용의 로직을 확인한 후에도이 부분 클래스를 호출하는 방법을 모르겠다. 단위 테스트를 할 때 데이터베이스에 접근하려고합니다.

+1

게시 한 제품 클래스가 부분적입니다. 부분 클래스를 호출하는 Product 클래스에 대한 하나 이상의 추가 구현이 있어야합니다. 우리가 그 모습을 모를 때 당신의 질문에 대답하기가 쉽지 않습니다. 또한 리포지토리와 컨트롤러가이 작업과 관련이 있다는 것을 알지 못해서 질문을 정리할 수 있습니까? –

답변

1

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

이것은 사실이 아닌 것 같습니다. 오류 인덱서 (이 []) 내 xaml ValidatseOnDataErrors 켜면 내 응용 프로그램에서 호출 된 것으로 나타납니다. 내 테스트 응용 프로그램에서, 그것을 켜기위한 장소가 부족한 것 같은데, 오류 인덱서는 IDataErrorInfo 비즈니스 객체에서 결코 체크되지 않습니다. 그래서 myObject.Name = string.Empty 설정; 이름 규칙을 확인하지 않습니다. 나는 아직도 이것을 할 길을 찾고있다. – Bob

+0

Bob과 동의하십시오. 이것은 완전히 작동하지 않습니다 ... – CamronBute

+1

그래서, 우리는 분명합니다 : 몇 가지 테스트를 게시하고, 당신은 그들을 통과시킬 수 없기 때문에, 당신은 내 downvotes 줄래? 인덱서뿐만 아니라 Error 속성에서 오류를 반환하십시오! 그런 다음 테스트가 통과합니다! –

2
내가 어설하기 위해 나중에 문을 사용하는 경우 매트에 의해 언급 된 솔루션은 나를 위해 작동

-

Assert.AreEqual ("Name is required.", _product [ "Name"]); -이 작품은 나를 위해

Assert.AreEqual ("Name is required.", _product.Error); -이 기능이 작동하지 않습니다.