2009-11-05 105 views
1

对不起,转发。如何用Nunit测试Nhibernate?

我使用NHibernate的ORM,并有这个类,我需要使用NUnit进行单元测试:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using NHibernate; 
using NHibernate.Cfg; 
using NutritionLibrary.Entity; 
using System.Data; 
using System.Data.SqlClient; 
using System.Collections; 

namespace NutritionLibrary.DAO 
{ 
    public class IngredientDAONHibernate : NutritionLibrary.DAO.IngredientDAO 

    { 

      private Configuration config; 
     private ISessionFactory factory; 

     public IngredientDAONHibernate() 
     { 

       config = new Configuration(); 
       config.AddClass(typeof(NutritionLibrary.Entity.Ingredient)); 
       config.AddClass(typeof(Entity.Nutrient)); 
       config.AddClass(typeof(Entity.NutrientIngredient)); 
         factory = config.BuildSessionFactory(); 

     } 


     /// <summary> 
     /// gets the list of ingredients from the db 
     /// </summary> 
     /// <returns>IList of ingredients</returns> 
     public System.Collections.Generic.IList<Ingredient> GetIngredientList() 
     { 
      System.Collections.Generic.IList<Ingredient> ingredients; 
      string hql = "from NutritionLibrary.Entity.Ingredient ingredient"; 

      ISession session = null; 
      ITransaction tx = null; 

      try 
      { 
       session = factory.OpenSession(); 
       tx = session.BeginTransaction(); 

       IQuery q = session.CreateQuery(hql); 

       ingredients = q.List<Ingredient>(); 
       tx.Commit(); 
      } 
      catch (Exception e) 
      { 
       if (tx != null) tx.Rollback(); 
       /*if (logger.IsErrorEnabled) 
       { 
        logger.Error("EXCEPTION OCCURRED", e); 
       }*/ 

      ingredients = null; 
      } 
      finally 
      { 
       session.Close(); 
       session = null; 
       tx = null; 
      } 

      return ingredients; 
     } 


    } 
} 

我开始与构造,但我得到了一些人建议我它不是真的有必要。所以这是我需要测试的方法。它查询数据库,并给我一个成分对象列表。我很难开始如何测试getIngredientList()方法。我有这个测试存根:

[TestMethod()] 
     public void GetIngredientListTest() 
     { 
      IngredientDAONHibernate target = new IngredientDAONHibernate(); // TODO: Initialize to an appropriate value 
      IList<Ingredient> expected = null; // TODO: Initialize to an appropriate value 
      IList<Ingredient> actual; 
      actual = target.GetIngredientList(); 
      Assert.AreEqual(expected, actual); 

     } 

我有很多的,我一定要考其他类似的方法,所以如果有人可能是一种足以帮助我开始使用这一点,我将有怎样一个基本理念在我的其他方法上实现单元测试。

再次感谢您的时间和建议。

回答

3

我可以给你的最好的建议是学习和使用S#arp architecture,它可以帮助你设置nUnit测试,DAO和DAL层以及更多。它还强制使用NHibernates Best Practices等等。您可以阅读关于S#arp体系结构的更多信息,以及如何设置它并在Bill McCafferty's blog(也是维护S#arp库的那个)上运行nUnit测试等。

注意:为了快速入门,S#arp libs提供了大量示例来向您展示它是如何完成的。如果S#arp看起来太多了,你可以按照上面NH最佳实践的链接,它有很多关于如何以统一和通用的方式设置nUnit测试的说明。

+0

+1非常有趣。 – 2009-11-05 05:10:11