創建測試頁始終是訪問 sql server 數據層并驗證輸入和輸出參數是否得到正確處理的好辦法。實際上,這是確保以后的生產解決方案中的 asp.net 頁和組件能夠按照預期方式工作的唯一辦法。這對于從解決方案中的某個層調用其他層時的驗證信任邊界和安全性問題尤其正確。
另外,在進行測試時,請勿拘泥于創建生產類接口。您只需測試目標方法。實際上,故意創建一些您不愿以之為最終生產解決方案的“丑陋”測試頁是一個好的策略!本文中,我創建了一些非常簡單的 asp.net 頁,其中包含一個測試記錄列表和一個用于添加、編輯和刪除測試記錄的輸入表單。
例如,以下是用于測試主題記錄的 webform 布局。您會發現,它包含錯誤消息或其他消息的狀態標簽、記錄計數標簽、顯示記錄列表的數據網格、用于輸入檢索時使用的記錄 id 的輸入框以及支持添加、編輯和刪除記錄的小表格(參見圖 10)。
圖 10:用于測試主題記錄的 webform 布局
在創建測試頁時,最好使代碼簡潔明了。我通常會為每個按鈕添加一小段代碼,以調用本地方法來處理數據庫操作。以下是 topictest.aspx 頁上 get record(獲取記錄)按鈕的代碼。
private sub btngettopic_click(byval sender as system.object,byval e as system.eventargs) handles btngettopic.click try dim id as integer = int32.parse(txqueryid.text) getitem(id) ' 進行數據庫調用 txid.text = txqueryid.text txtitle.text = mtitle txdescription.text = mdescription lbstatus.text = "success!" catch ex as exception lbstatus.text = ex.message end try end sub 請注意,本方法中實際執行的唯一操作是由 getitem(id) 方法調用處理的。它執行數據庫調用并使用返回的值設置本地變量。以下是 getitem 方法的代碼。請注意,它使用了大量的 sqlparameter 對象來處理輸入和輸出值。
private sub getitem(byval id as integer) try pr = new sqlparameter("return_value", sqldbtype.int) pr.direction = parameterdirection.returnvalue dim ptitle as sqlparameter = new sqlparameter with ptitle .direction = parameterdirection.output .dbtype = dbtype.string .parametername = "@title" .size = 30 end with dim pdescription as sqlparameter = new sqlparameter with pdescription .direction = parameterdirection.output .dbtype = dbtype.string .parametername = "@description" .size = 500 end with
cd = new sqlcommand
with cd .commandtext = "topicsgetitem" .commandtype = commandtype.storedprocedure .parameters.add(new sqlparameter("@admincode", "adm")) .parameters.add(new sqlparameter("@id", id)) .parameters.add(ptitle) .parameters.add(pdescription) .parameters.add(pr) .connection = cn .connection.open() .executenonquery() .connection.close() end with
' 檢查返回代碼 if not pr.value is nothing then select case int32.parse(pr.value) case 100 : throw new applicationexception("access violation") case 101 : throw new applicationexception("invalid id") end select end if ' 設置返回值 mtitle = ptitle.value.tostring() mdescription = pdescription.value.tostring() catch ex as exception throw new exception(ex.message, ex) end try end sub getitem 方法的另一個重要方面是使用了返回值參數。它在前幾行代碼中進行聲明,并在執行存儲過程后進行檢查。請注意,我檢查了已知錯誤代碼 100 和 101。有關其他錯誤的處理方法,我們將在以后介紹如何創建成熟的中間層時進行介紹。問題在于,我要利用返回值并在需要時拋出一個自定義異常。
對于本解決方案示例,我最終生成了六個 web 表單,并用它們測試了將近 30 個存儲過程和自定義函數。您可在本文開始部分列出的下載軟件包中找到所有這些完成的表單。
現在我們已經定義了表、創建了存儲過程和函數并生成了 asp.net web 表單,因此可以使用 visual studio .net 2003 生成數據庫層的安裝腳本了。數據庫管理員(有時是您自己)可以將此腳本應用到生產服務器上。