【问题标题】:Unit Testing methods with Trace.Write() in ASP.NET with MSTest使用 MSTest 在 ASP.NET 中使用 Trace.Write() 进行单元测试方法
【发布时间】: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


    【解决方案1】:

    区分测试环境和实时环境的快速而肮脏的方法:

    If HttpContext.Current Is Nothing Then
    

    您的 Trace.Write 语句引发 NullReferenceException 的原因可能是因为 Trace 依赖于 HttpContext。如果是这样,您可以模拟 HttpContext:

    <TestInitialize()>
    Public Sub Setup()
        'Since this is not a real web app, we need to mock at least
        'the current HttpContext
        HttpContext.Current = New HttpContext( _
            New HttpRequest("", "http://tempuri.org", ""), _
            New HttpResponse(New StringWriter()) _
        )
    End Sub
    

    【讨论】:

    • 谢谢!检查HttpContext.Current 有效,但我当然必须更改调用Trace.Write 的每一行代码。我更喜欢你的第二个选项,但即使在我的 TestSetup 方法中提供了 HttpContext 之后,我仍然会得到 NullReferenceException
    • 您能否提供NullReferenceException 的完整堆栈跟踪?
    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多