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?
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With