Unit Testing / Mocking HttpContext Without Using Any Mock Framework
Sep 7, 2010
Since I'm having problem with unit testing RenderPartialViewToString() with Moq framework [URL] I'm thinking about getting my controller directly, without using Moq for these particular test, however, how do I mocks (or set) the HttpContext for my test without using any Moq framework?
I need to able to do something similar to this, without Moq of course:
var mockHttpContext = new Mock<ControllerContext>();
mockHttpContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("n1\test");
mockHttpContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
View 2 Replies
Similar Messages:
Apr 3, 2011
I'm using the mock framework to unit test some methods. I came across some methods that use delegates. I did not find a way to setup these delegates to return the objects that I want. The mock framework does not support it as far as I know. Is this supported in other mock frameworks like nMock?
View 3 Replies
Nov 11, 2010
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?
View 3 Replies
Feb 10, 2010
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.
View 3 Replies
May 17, 2010
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".
It returns count "3" instead of "4".
View 3 Replies
Aug 25, 2010
I'm looking for as comprehensive as possible of a mock replacement and wrapper for the ASP.NET HttpContext in my applications. A comprehensive mock replacement could potentially increase the testability of my ASP.NET web applications substantially, without necessitating migrating every application to more-testable frameworks such as MVC.
Some of the features I am most interested in seeing in an HttpContext wrapper and mock framework include:
Serialized session storage (e.g., .Session).
Serialized application-scoped storage (e.g., .Application).
Per-request item storage (e.g., .Items).
HttpRequest data, such as referrers, request Uri, server variables, post data, etc.
HttpResponse data, such as status codes and content.
Local file resolution (e.g. Server.MapPath)
VirtualPathUtility for application-relative URL path resolution, which has a dependency on the ASP.NET runtime.The identity and principal (e.g., .User) for validating authentication/authorization rules.The AllErrors collection for testing error resolution in HttpModules and Global.asax.I considered writing my own interface, wrapper, and mock; however, I believe such must already exist. The variety of mock frameworks is a little overwhelming for a first-timer to absorb.
What is the most comprehensive HttpContext wrapper and mock?
View 2 Replies
Oct 26, 2010
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?
View 5 Replies
Jul 15, 2010
I'm writing unit tests in ASP.NET 4.0 web application (ASP.NET Forms, not MVC). There are several spots in the code where I call the ServerVariables collection to call variables like REMOTE_ADDR. Since my unit tests do not actually initiate HttpRequests when executing my code, things like ServerVariables are Null and therefore error when I try to call HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
All the solutions I've found to address this issue refer to MVC and so they assume that HttpRequest derives from HttpRequestBase, which it does in MVC but not in ASP.NET Forms.I tried using Moq but you can't mock a sealed class, and HttpRequest is unfortunately sealed with no interface.
View 1 Replies
Feb 11, 2010
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.
View 1 Replies
Mar 21, 2011
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).
View 3 Replies
Feb 4, 2010
I want to mock ASP.NET 3.5 behavior in order to unit test my WebControls: I want to test how they perform with mock data with existing system of events. Basically I want to test generated result HTML based on input mock data. How to do it? I looked into NMock, but it doesn't suit my needs for 2 reasons:
It just runs ASP.NET server in separate process in order to get resulting HTML; My WebControls output HTML as a text on render, so there are elements which do not correspond to any ASP.NET control (except LiteralControl in some cases). Also, I have huge legacy system, so rewriting everything for MVC won't work for me (too much job), I need to write unit tests to existing controls.
View 1 Replies
Feb 23, 2011
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.
View 2 Replies
Mar 28, 2011
I've see n a lot of discussions surrounding HttpSessionState and asp.net MVC.I'm trying to write tests for an asp.net application and to mock the HttpSessionState and if so, how?I'm currently using Rhino Mocks and Nunit
View 1 Replies
May 6, 2010
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]....
View 5 Replies
Apr 3, 2011
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.
View 4 Replies
Mar 18, 2011
In MVC, the unit testing is primarily surrounding the controllers. The Model is rarely tested, and the View not at all. What is the consensus on this?
View 13 Replies
Mar 2, 2010
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.
View 4 Replies
Aug 10, 2010
I need to implement my own Profile properties and was going to inherit from System.Web.Profile.ProfileBase to achieve this.
What I don't understand is how to best unit test this Profile class in isolation without hitting the database.
View 1 Replies
Jan 27, 2011
I'd like to write some code and then just write the unit tests for the important stuff.
I know the tools. I know how to write a unit test.
I wrote some code (couple off classes) and I don't know where to start. I'm missing the semantic.
How to pick up what to unit test ?
Should I unit test every class extra ?
Should I try to simulate every possible variation of method's parameters ?
View 2 Replies
Aug 15, 2010
I need to fake HttpContext.Current.Application table to access it from my unit tests.I need to store my data somewhere. I thought that I can just pass instance of NameValueCollectionBase but as I descover this base type has no indexer so it's too complicated to use. So what about faking this part of HttpContext? Is it possible? How can I make it? Will be NUnit.
View 2 Replies
Aug 13, 2010
I want to write a unit test which tests the function of a class called UploadedFile. The problem I face is this class' static constructor uses HttpContext.Current property and because I am running my unit test from a class library I do not have an HttpContext at the testing time.
Look at my static constructor:
static UploadedFile()
{
if (HttpContext.Current == null)[code]....
What should I do in my testing environment so that HttpContext.Current won't be null and I can successfully set this:
HttpServerUtility server = HttpContext.Current.Server;
View 2 Replies
Sep 3, 2010
I want to imlement the Unit Testing in my asp.net web application.How to identify the scope of this. I mean, How should i start on this front.
View 2 Replies
Mar 3, 2011
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.
View 2 Replies
Feb 18, 2011
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.
public override void GenerateCode(AssemblyBuilder assemblyBuilder)
{
string outputName = VirtualPath.Substring(VirtualPath.LastIndexOf('/') + 1);
outputName = outputName.Substring(0, outputName.LastIndexOf('.'));
_compilationContext = (CompilationContext)HttpContext.Current.Items[outputName];
var tw = assemblyBuilder.CreateCodeFile(this);
tw.Write(_compilationContext.Content);
tw.Flush();
foreach (var assembly in CompilerServices.GetLoadedAssemblies().Where(a => !a.IsDynamic))
assemblyBuilder.AddAssemblyReference(assembly);
}
View 1 Replies
Sep 27, 2010
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 ?
View 2 Replies