【发布时间】:2013-11-12 19:18:07
【问题描述】:
Public Class PhotoUploadController
Public ReadOnly Property IsMobileDevice As Boolean
Get
Return ControllerContext.HttpContext.GetOverriddenBrowser.IsMobileDevice
End Get
End Property
Function SavePhoto(model As PhotoUploadModel) As ActionResult
If Not String.IsNullOrWhiteSpace(Request.Files(0).FileName) And IsMobileDevice Then
Return View("Index", model)
End If
End Function
End Class
<TestMethod()>
Public Sub SavePhoto_Test()
Dim permissions As New List(Of String)
permissions.Add(Constants.VIEW_ACCOUNTS)
Dim mUser As New MockUser(ListOfPermissions:=permissions)
Dim controller As PhotoUploadController = New PhotoUploadController(mUser, New PhotoRepository)
System.Web.HttpContext.Current = New HttpContext(New HttpRequest("test", "http://www.yahoo.com/accounts", ""), New HttpResponse(New System.IO.StringWriter()))
Dim browserMock = MockRepository.GenerateStub(Of HttpBrowserCapabilities)()
browserMock.Expect(Function(b) b.IsMobileDevice).Return(True)
System.Web.HttpContext.Current.Request.Browser = browserMock
Dim currentContext As HttpContextBase = MockRepository.GenerateStub(Of HttpContextWrapper)(System.Web.HttpContext.Current)
currentContext.Expect(Function(fn) fn.Request.Files(0).FileName).Return("test.txt")
'If I comment out the two lines above and uncomment the below line the IsMobile is set in the SavePhoto actionresult otherwise it is null.
'Dim currentContext As HttpContextBase = New HttpContextWrapper(System.Web.HttpContext.Current)
controller.ControllerContext = New ControllerContext(currentContext, New System.Web.Routing.RouteData(), controller)
Dim model As New PhotoUploadModel(mUser)
Dim result As ActionResult = controller.SavePhoto(model)
Assert.IsNotNull(result)
Assert.IsInstanceOfType(result, GetType(ViewResult))
End Sub
【问题讨论】:
-
根据例外情况,它不是模拟对象。您需要创建模拟对象。如果你使用 Rhino Mock,你可以使用 MockRepository.GenerateStub
(); ? -
当我在代码中调用此对象时,新错误 ControllerContext.HttpContext.GetOverriddenBrowser.IsMobileDevice 为 null。为什么 GenerateStub 会删除我传递给 System.Web.HttpContext.Current 的浏览器信息?如果我删除 GenerateStub 并将这个 Dim currentContext 添加为 HttpContextBase = New HttpContextWrapper(System.Web.HttpContext.Current)。 ControllerContext.HttpContext.GetOverriddenBrowser.IsMobileDevice 有一个值。我添加浏览器模拟代码的原因。
-
嗨@user2868558,您能否使用完整的单元测试和被测系统提供/更新您的问题(当然省略任何敏感信息)。没有看到你的代码就很难给你一个完整的答案。
-
我取出了一些代码。出于某种原因,这里的编辑不喜欢我写的一些项目。所以它看起来不像上面的代码。我设置了 IsMobileDevice 但我需要模拟上下文以添加文件名。出于某种原因,我不能两者都做。
标签: asp.net-mvc unit-testing rhino-mocks