How to mock application path when unit testing Web App

后端 未结 6 1346
囚心锁ツ
囚心锁ツ 2021-01-04 12:35

I am testing code in a MVC HTML helper that throws an error when trying to get the application path:

//appropriate code that uses System.IO.Path to get direc         


        
6条回答
  •  無奈伤痛
    2021-01-04 13:02

    For what it's worth, I ran up against the same error and followed it through the System.Web source to find it occurs because HttpRuntime.AppDomainAppVirtualPathObject is null.

    This is an immutable property on the HttpRuntime singleton, initialized as follows:

    Thread.GetDomain().GetData(key) as String
    

    where key is ".appVPath". i.e. it comes from the AppDomain. It might be possible to spoof it with:

    Thread.GetDomain().SetData(key, myAbsolutePath)
    

    But honestly the approach in the accepted answer sounds much better than mucking around with the AppDomain.

提交回复
热议问题