T4MVC and testing with MvcContrib.TestHelpers gett

2019-07-20 22:46发布

问题:

My issues my be due to my n00bness in the MVC land, but I'm trying to write a test for a function in a controller that was generated with T4MVC. So I thought I'd use the MvcContrib.TestHelper as well.

I new up a TestControllerBuilder and my controller, when I try and call InitializeController on it I get an exception:

System.TypeInitializationException: The type initializer for 'Images' threw an exception. ---> System.Web.HttpException: The application relative virtual path '~/Content/Images/add.gif' cannot be made absolute, because the path to the application is not known.

Ok, it's trying to get the images and they are not in the relative path of the test executable...how do I tell it?

I tried this T4MVCHelpers.ProcessVirtualPath() but pretty much everything I try in there throws an error when it calls the VirtualPathUtility.ToAbsolute() method.

I have no doubt I'm doing something wrong. Am I incorrect in my understanding that the TestControllerBuiler will setup my mock HTTPContexts for me? Can I tell it to ignore the image stuff?

Please help a n00b out. A simple example on how to use the TestHelper and ProcessVirtualPath would be awesome.

Update

For those who get a similar error, my reason was because the httpcontext was being used in the controller constructor. In my case it was erroring on a strong typed image path T4MVC generated.

回答1:

You can provide your own method for T4MVC to use by setting the ProcessVirtualPath delegate.

The anonymous method below keeps the spirit of the original implementation.

T4MVCHelpers.ProcessVirtualPath = p => VirtualPathUtility.ToAbsolute(p, "/App");