【发布时间】:2013-06-06 05:09:20
【问题描述】:
我正在尝试向一些遗留代码添加一些单元测试。很多函数都以Trace.Write开头
Function FormatDate(ByVal inputAsString As String) As String
Trace.Write("Function FormatDate")
当我针对全套 ASP.NET 单元测试属性运行测试时,花费的时间太长:
<TestMethod(), _
HostType("ASP.NET"), _
UrlToTest("http://localhost:25153/WebSite1"), _
AspNetDevelopmentServerHost("C:\WebSite1", "/WebSite1")>
Public Sub FormatDateTest()
作为回应,我刚刚测试了该类本身的一个实例:
<TestMethod(), _
Public Sub FormatDateTest()
这工作很快,但当我到达Trace.Write() 时,我收到“对象引用未设置为对象的实例”错误
如果我正在运行单元测试而不是调用跟踪,有什么方法可以测试吗?我可以模拟一个 html 对象以使其不会引发异常吗?我可以直接超越异常吗?我应该摆脱 Trace 吗?我有点想将测试保留在 MsTest 中,因为我在一个非常严格的 Microsoft 衍生产品商店。
更新
这是来自NullReferenceException 的堆栈跟踪
at System.Web.UI.UserControl.get_Trace()
at Applications.Interface.UCparent.FormatDate(String inputAsString, Boolean isFuzzy, Char& precision)
in \\...\UCparent.ascx.vb:line 285
Trace.Write 方法返回调用它的页面的System.Web.TraceContext。本质上,写Page.Trace.Write是一样的
问题是,当使用@Ross Presser 的建议将HttpContext.Current 添加到单元测试设置中时,Page.Trace Is Nothing = True 仍然是这种情况
'This Works
HttpContext.Current.Trace.Write("HttpContext.Current")
'This Doesn't
Page.Trace.Write("Page.TraceContext")
'This Doesn't
Trace.Write("Page.TraceContext")
我可以进入并更改所有 Trace.Write 方法以使用 HttpContext 而不是默认页面上下文,但这会遇到与之前相同的问题。此外,Page 上的 Trace 属性没有设置器,因此如果不自然地继承页面,似乎很难只给页面一些上下文。
【问题讨论】:
标签: asp.net unit-testing mstest