0

I'm trying to add some unit tests to some legacy code. Many of the functions begin with Trace.Write

Function FormatDate(ByVal inputAsString As String) As String
    Trace.Write("Function FormatDate")

When I run Tests against the full set of ASP.NET Unit test attributes, it takes too long:

<TestMethod(), _ 
HostType("ASP.NET"), _ 
UrlToTest("http://localhost:25153/WebSite1"), _
AspNetDevelopmentServerHost("C:\WebSite1", "/WebSite1")>
Public Sub FormatDateTest()

In response, I've just been testing an instance of the class itself:

<TestMethod(), _ 
Public Sub FormatDateTest()

This works quickly, but I get an "Object Reference No Set to an instance of an Object" error when I arrive at Trace.Write()

Is there some way I can test if I'm running unit tests and not call trace? Can I mock an html object so that it doesn't throw an excpetion? Can I push right past the exception? Should I just get rid of Trace? I'd kind of like to keep the tests within MsTest since I'm in a pretty strictly Microsoft derivitive product shop.

Update

Here's the stacktrace from the 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

The Trace.Write method returns the System.Web.TraceContext of the Page on which it is called. Essentially, it is idential to writing Page.Trace.Write

The problem is, when using @Ross Presser's suggestion of adding HttpContext.Current to the Unit Test Setup, it's still the case that 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")

I can go in and change all the Trace.Write methods to use the HttpContext intstead of the default page context, but that runs into the same problem as earlier. Also the Trace property on Page has no setter, so it seems difficult to just give the page some context without it naturally inheriting it.

4

1 回答 1

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
于 2013-06-05T14:35:53.903 回答