MVC :: Unit Testing Custom RequestValidator For Class?
Jun 30, 2010
I wrote a custom RequestValidator implementation to deal with W.I.F. security tokens. Now I am trying to write a unit test for this class. This method is protected internal. Even using InternalsVisibleToAttribute, I am having no luck being able have my unit test compile against my implementation of:
bool
IsValidRequestString(HttpContext context,
string value, RequestValidationSource rvs,
string
collectionKey, out
int validationFailureIndex)
2. The HttpContext class used by this method is sealed so I am not sure how to mock one up with a mocking framework (i.e. rhinomocks in my case).
How can BuildProvider's GenerateCode method be tested. I created a BuildProvider and now I want to unit test it. Is it possible? Initial question was not clear enough. I don't want to stub AssemblyBuilder, I want to mimic asp.net request. I want to make sure that VirtualPathProvider and BuildProvider work fine together.
One more clarification, I am not really interested in generated code from build provider, it is used only to kick-start compilation in medium-trust environment, I already have a code, I need build provider just so I could compile since CodeDomProvider is not accessible directly in medium trust.
I'm using a simple base class for my controller that sets a piece of ViewData and makes use of the HttpContext. My understanding is that I need to put this code in Initialize() or OnActionExecuting(). I tried both, but believe Initialize() is what I want.
This works when running the app in VS just fine.
I wrote a unit test that calls the action and checks the ViewData for the expected value. When unit testing, neither method is called.
I want to unit test my rendering engine for an ASP.NET app. I have some custom controls created in that app. Most of those control rely on having CreateChildControls() method called by the ASP.Net engine wheather during initial call or a postback.When running a test CreateChildControls() does not get called and the control is in an "invalid" state.
As a workaround to get the tests going I explicitly call some other public method that calls EnsureChildControls() in it. This in effect causes CreateChildControls() to be executed and the control being initialized properly (just as it would normally when hosted on web server). I would like to get rid of that extra method call and the control to still be in a proper state for testing.
Recently for a class to implement unit test for one of its private methods I used PrivateObject by creating private accessor instead of refelection, to which i received a code review comment as below
"My main concern with Private Object is the use of object[] in constructor. It replaces strong typing enforced by compiler with JavaScript-style run-time error detection.Consequently , personally, I would not recommend it."
Comments above confused me beacuse as per my understanding reflection also needs the object[] to invoke any method.
I'm using VSTS 2K8 and I've set up a Unit Test Project. In it, I have a test class with a method that does a simple assertion. I'm using an Excel 2007 spreadsheet as my data source.
My test method looks like this:
[Code]....
As indicated in the method decoration attributes, my Excel spreadsheet is on my local C:/ Drive. In it, the sheet where all of my data is located is named "Sheet1".I've copied the Excel spreadsheet into my project and I've set its Build Action = "Content" and I've set its Copy to Output Directory = "Copy if Newer".
When trying to run this simple unit test, I receive the following error:
The unit test adapter failed to connect to the data source or to read the data. For more information on troubleshooting this error, see "Troubleshooting Data-Driven Unit Tests" (http://go.microsoft.com/fwlink/?LinkId=62412) in the MSDN Library. Error details: ERROR [42S02] [Microsoft][ODBC Excel Driver] The Microsoft Office Access database engine could not find the object 'Sheet1'. Make sure the object exists and that you spell its name and the path name correctly.
I've verified that the sheet name is spelled correctly (i.e. Sheet1) and I've verified that my data sources are set correctly.Web searches haven't turned up much at all. [Code]....
I have been looking at the unit testing topic and honestly I have never yet seen it in a live application.
Im a little foggy on the subject.... A simple example is if I am populating a listbox with data, I would know through debugging if the data is being populated and if it wasnt it would probably be easy to figure out why. Futhermore I couldnt possibly put it in production if it wasnt work so, why would I need to do a unit test? I dont see the point of it.
I'm using the Moq framework to do my unit testing. I'm following some really useful instructions outlined here to mock the httpcontext, specifically for the purposes of testing the url referrer:[URL]
Everything seems to compile fine, however when running the test I get the following error:
System.Web.HttpException: Invalid use of SimpleWorkerRequest constructor. Application path cannot be overridden in this context. Please use SimpleWorkerRequest constructor that does not override the application path..
When analyzing I find the error seems to be thrown at the following line:
var wr = new SimpleWorkerRequest("", "", "", "", writer); I'm not sure what to make of this. What is the SimpleWorkerRequest and how does it work in creating the HttpContext in Moq?? Why is my use of it invalid according to the debugger??
UPDATE: Here is the complete method I use taken from the website above
public static HttpContextBase FakeHttpContext() { var httpContext = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); var response = new Mock<HttpResponseBase>(); var session = new Mock<HttpSessionStateBase>(); var server = new Mock<HttpServerUtilityBase>(); var cookies = new HttpCookieCollection(); httpContext.Setup(x => x.Server).Returns(server.Object); httpContext.Setup(x => x.Session).Returns(session.Object); httpContext.Setup(x => x.Request).Returns(request.Object); httpContext.Setup(x => x.Response).Returns(response.Object); response.Setup(x => x.Cookies).Returns(cookies); httpContext.SetupGet(x => x.Request.Url).Returns(new Uri("http://www.csuci.edu")); httpContext.SetupGet(x => x.Request.UrlReferrer).Returns(new Uri("http://www.csuci.edu")); //var writer = new StringWriter(); //var wr = new SimpleWorkerRequest("", "", "", "", writer); //HttpContext.Current = new HttpContext(wr); return httpContext.Object; }
I commented out the problem lines, that seemed to fix it, but I'm still not sure what those lines were supposed to do and why they were causing error.
I created a new ASP.NET MVC application and the accompanying unit tests that can be generated automatically. I created a new Controller method and tried to wire up a test. The test failed, and I tried to step through the test code to find out the state of certain variables. The breakpoint showed as being set, but it never was hit.
I did a Google search on this, and there are many other people wondering the same thing - why doesn't this work? The answers have been sketchy at best. The most proliferant seems to be that the unit tests are run in the production configuration instead of the debug configuration, and so several steps are required to get breakpoints to work. Seriously? This is something I would expect to be enabled by default. What good is test code you can't step through? Why create a set of unit tests that require you to jump through several hoops to get this very basic feature running? NUnit (and I suppose others) don't have this issue.
how to get the breakpoints to work were completely different than all the others, and I'd like to know if anyone has an idea of how to enable debugging of the unit tests that are included in Visual Studio 2008.
I would like to have information on the available unit testing frameworks in .NET realm. Especially the ones which are suitable for ASP.NET (C# .NET 3.5).
I've made a custom model, and I want to mock it. I'm fairly new to MVC, and very new to unit testing. Most approaches I've seen create an interface for the class and then make a mock that implements the same interface. However I can't seem to get this to work when actually passing the interface into the View. Cue "simplified" example:
[code]...
Upon a HttpPost I get a "Cannot create an instance of an interface" exception. I seems that I can't have my cake (passing a model) and eat it (pass mock for unit testing). Maybe there's a better approach to unit testing models bound to views?
How can I render a razor view in a Unit Test?When I change for instance a html helper method, I sometimes forget to update all the views which uses that html method. So the view I forgot generates a YSOD.I would like to create unit tests that renders a view and fails if I forgot to make the neccecary updates.
is there some property where I can tell Code First to work against a static in memory lists ?
I am thinking on creating some generic class to work against code first like in the ASP.NET MVC Unleashed book and I was wondering if maybe there is simple way or something which is already made instead of me creating all the generic fakes ?
+ if i use Code First , should I still create a repository to work against this domain model ?
I have a class which I store in session. Lets say Class A, having an attribute theList. I have a member function that adds an item to theList and returns the count of my list.So I mock my class and set theList to "1,2,3" for my unit test, and test my add function by adding "4".
I'm currently testing my application and am stuck on trying to figure out how to create a custom fake URL referrer. I've tried to hard code it, but am getting an error that it is read-only. Here is what I've tried so far:
fakeController.HttpContext.Request.UrlReferrer.AbsolutePath = "http://www.yahoo.com"; as well as, fakeController.Request.UrlReferrer = "http://www.yahoo.com";
I've searched the web for some ideas on how to create a fake/mock URL referrer for my fake controller, but have had no luck.
Note: I'm using Visual Studios built-in unit testing facilities.
UPDATE:
I would be more than willing to use any other unit testing system outside of Visual Studio, unfortunately here at my work we are only allowed to use Visual Studio's built-in system, so I gotta work with what I've got.
I want to write unit tests for a web service. I create my test project, reference my web project (not service reference, assembly reference), then write some code to test the web services - they work fine. However, there are some services which make sure the user is logged in to the web application by using HttpContext.Current.User.Identity.IsAuthenticated. In the context of the tests, there is no such thing as HttpContext, so the tests always fail. How should these kinds of web services be unit tested?
I am using the Nhibernate with MVC. In the controller i am getting the model from the HttpSession. How can i set the model from controller Unit testing method.
When I doing unit testing, I suddenlt got error message like:
The test adapter ('Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=10.0.0.0, Culture=neutral, ublicKeyToken=b03f5f7f11d50a3a') required to execute this test could not be loaded. Check that the test adapter is installed properly. Operation is not valid due to the current state of the object.
I had this before, to resolve this is to set default run in my testrun.config. After that, I can run unit testings, but I got error :
System.NullReferenceException: Object reference not set to an instance of an object.
The problem is that unit testing cannot initiate DBConnection. Here is my DBconn.vb: