Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Code that calls VirtualPathUtility.ToAbsolute

I'm trying to unit test some code that calls into VirtualPathUtility.ToAbsolute.

Is this possible with the unit testing tools provided with VS 2008? If not, is it possible with a later version of Visual Studio?

like image 680
ilivewithian Avatar asked Mar 17 '09 17:03

ilivewithian


People also ask

How do you do unit testing?

To get started, select a method, a type, or a namespace in the code editor in the project you want to test, right-click, and then choose Create Unit Tests. The Create Unit Tests dialog opens where you can configure how you want the tests to be created.

Does test is not included in unit testing?

A test is not a unit-test if: it communicates with a database. it cannot run in parallel with other tests. uses the "environment" like registry or file system.

What is a unit test stackoverflow?

Unit testing is the process of writing code to test the behavior and functionality of your system. Obviously tests improve the quality of your code, but that's just a superficial benefit of unit testing.


1 Answers

We're well past VS 2008 but for anyone who is still grappling with this issue, I've found a solution on: http://forums.asp.net/t/995143.aspx?Mocking+HTTPContext+object.

Use the following code in your test init to override the default AppDomain values. (The VirutalPathUtility static methods will use your new values.)

[TestInitialize]
public void Initialize()
{
    // Fake out env for VirtualPathUtility.ToAbsolute(..)
    string path = AppDomain.CurrentDomain.BaseDirectory; 
    const string virtualDir = "/";
    AppDomain.CurrentDomain.SetData(".appDomain", "*");
    AppDomain.CurrentDomain.SetData(".appPath", path);
    AppDomain.CurrentDomain.SetData(".appVPath", virtualDir);
    AppDomain.CurrentDomain.SetData(".hostingVirtualPath", virtualDir);
    AppDomain.CurrentDomain.SetData(".hostingInstallDir", HttpRuntime.AspInstallDirectory);
    TextWriter tw = new StringWriter();
    HttpWorkerRequest wr = new SimpleWorkerRequest("default.aspx", "", tw);
    HttpContext.Current = new HttpContext(wr);
}
like image 190
Jon Kerr Avatar answered Sep 22 '22 03:09

Jon Kerr