按Lee的原例實作的測試解決方案。是進行以後各部分學習的基礎。
(一)建立Domain類庫項目。
這個項目主要用于持久類與嵌入的映射檔案的存在庫。
還以Customer為例子。
·資料庫中主要的三個字段:customerid,firstname,lastname
·持久類Customer的屬性:Unid(這裡用Unid,不用與資料庫的customerid,主要目的是更好的了解mapping關系);FirstName;LastName
·引用類庫:可能會用到Iesi.Collections.dll
這裡代碼我就不貼了。
說明:映射檔案要是嵌入的類型。
(二)建立Data類庫項目。
這個項目主要用于建立資料(NHB)與Mapping的關系。
·NHBHelper類:用于擷取ISession(NHB工作單元)
·NHBControl類:用于資料邏輯(Isession——mapping)
·NHibernate.cfg.xml:用于配置資料庫類型、映射類及其它。(現在好多節點沒深入了解意思)
·引用類庫:NHibernate.dll;Castle.DynamicProxy2.dll(Castle代理必須);Domain.dll(持久類及mapping)
貼出兩個類:
public class NHBHelper
{
private ISessionFactory SessionFactory;
public NHBHelper():this(@"E:\test8\NHBTraffic\Data\NHibernate.cfg.xml")
{ }
public NHBHelper(string strPath)
{
SessionFactory=GetCurrentSession(strPath);
}
private ISessionFactory GetCurrentSession(string strPath)
return (new Configuration()).Configure(strPath).BuildSessionFactory();
public ISession GetSession()
return SessionFactory.OpenSession();
}
注意:要注意NHibernate.cfg.xml檔案的路徑。因為這個示例還要在Web項目裡應用,是以我設定了路徑
public class NHBControl
#region Init
private ISession _Session;
NHBHelper helper = new NHBHelper();
#endregion
#region create
public NHBControl()
_Session = helper.GetSession();
}
#endregion
這個類沒有什麼可說明的。
(三)建立SelfTest類庫
主要用于測試
我添加了一個TestHql類,用于測試。
·引用類庫:Domain.dll;Data.dll;nunit.framework.dll
(四)為解決方案建立網站Web
·引用類庫為:Domain.dll;Data.dll
(五)測試
測試(1)通過Unid傳回Customer執行個體
NHBControl類
public Customer GetCustomerById(int Iid)
{
return _Session.Get<Customer>(Iid);
TestHql類
[Test]
public void TestGetOne()
Customer customer = cc.GetCustomerById(100);
Assert.IsNull(customer);
Web頁
protected void Page_Load(object sender, EventArgs e)
Customer customer = cc.GetCustomerById(1);
string s = customer.FirstName;
Response.Write(s);
成功。
如果要添加其它的資料操作及hql測試,我全加在NHBControl類
而測試就在TestHql類進行。
好了,有了這個解決方案,以後的測試可以明了的進行了。
這裡不提供源碼下載下傳,因為想讓大家自己手動建立測試項目,并且自己排程通過,來解決其中的各個問題。
參考Lee的系列。詳細請參見 YJingLee's blog。
http://www.cnblogs.com/lyj/archive/2008/10/30/1323099.html部落格園大道至簡
http://www.cnblogs.com/jams742003/轉載請注明:部落格園