使用MSTest在ASP.NET中使用Trace.Write()进行单元测试方法

时间:2013-06-05 14:29:15

标签: asp.net unit-testing mstest

我正在尝试将一些单元测试添加到一些遗留代码中。许多功能都以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对象,以便它不会引发一个激发吗?我可以直接推过例外吗?我应该摆脱追踪吗?我有点想把测试保留在MsTest中,因为我是一个非常严格的微软衍生产品商店。

更新

以下是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方法返回调用它的Page的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而不是默认的页面上下文,但这会遇到与之前相同的问题。 Trace上的Page属性也没有setter,所以如果没有自然继承它,就很难给页面一些上下文。

1 个答案:

答案 0 :(得分:1)

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

If HttpContext.Current Is Nothing Then

可能是你的Trace.Write语句抛出NullReferenceException的REASON是因为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
相关问题