创建 ASP.NET 测试页
创建测试页始终是访问 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 |
| 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 |
http://dev.xuezhishi.net/website/NET/2007-10-17/20786.html