MVC 3: How to Mock an instance of WebViewPage<T>? - asp.net-mvc

I'm currently using the Rhino Mocks mocking framework. How do you mock an instance of WebViewPageBase AND its Model with Rhino Mocks or any other mocking framework? When I run the following unit test, an exception is thrown when attempting to access the WebViewPageBase.Model property.
var repo = new Rhino.Mocks.MockRepository();
System.Web.Mvc.WebViewPage<IEnumerable<Tuple<string>>> page = repo.DynamicMock<System.Web.Mvc.WebViewPage<IEnumerable<Tuple<string>>>>();
Assert.IsNotNull(page.Model);//exception thrown, not a fail on Assert
Would this be more easily accomplished with a different mocking framework?

Scott Hanselman has a great write-up on mocking MVC 3 classes with Rhino here:
http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx

Are you sure you want to get the view page this way as it won't have a model etc because it has not all been setup.
More typically you would test the controller and inspects its return value which would contain the rendered html if you want to check that.
Assuming you really do want to unit test this, then I don't see anything intrinsically wrong with your code. You could try Moq instead of Rhino which is what I use.
This question may also be pertinent to your issue without how Rhino handles abstract classes:
Mock abstract class default behaviour with Rhino

Related

How to UnitTest System.Web.Mvc.Html.InputExtensions.TextBoxFor?

Edit : I am not trying to UnitTest TextBoxFor, but the code that uses it, However mocking objects and passing it to the code causes null reference exception without any hints on what property did not have a value, som properties like Request can not even be mocked.
How to UnitTest System.Web.Mvc.Html.InputExtensions.TextBoxFor ?
From googling around it seems that TextBoxFor is not UnitTestable, one can not mock the required parameters and get a result back, what is a unit testable alternative ?
The overuse static functions in MVC goes everything OO. The base units of in MVC are not even unit testable, or is there a another way to test?
Here is a link to one of the articles I used try to mockup objects so that I can test the custome Html Helper
http://community.embarcadero.com/blogs/entry/unit-testing-html-helpers-for-aspnet-mvc-38638

ControllerFactory : Entity Framework

I recently followed Stephen Walther through creating a generic repository for your data models using the Entity Framework with the following link, http://bit.ly/7BoMjT
In this blog he briefly talks about creating a generic repository and why it's suggested to do so (to be clear of friction). The blog itself doesn't go into great detail on how to inject the GenericRepository into your project for that you'll need to download his source code of Common Code. However, once I finally understood the importance of the Repository pattern, and how it makes a difference in the data models I create in ASP.Net MVC I was wondering if I could do something similar to my Controllers and Views?
Can I create a ControllerRepository or ControllerFactory(as I've Bing'd it) and create a generic controller with 5 ActionResults and depending on what I inject into my GenericRepository datamodel (i.e. I have DellXPSComputers, GateWayComputers, HPComputers as a single db datamodel)
And actually have only one controller besides the Generic one I create that will go and grab the right datamodel, and view?
If so, what is the best way to implement this?
You could create a generic controller factory, but I don't see many scenarios why you'd ever want to. Except in your tests and redirects, you'd never be calling a controller method directly (vs. a repository method which you're calling in many places).
Yes! You absolutely can!
I've done it in the past with great success. The result is that you end up with a web application layer surfacing your repos with almost no code (just what's necessary to provide CRUD services for your entities).
Ultimately, you'll end up with something like this in your implementation of CreateController:
Type controllerType = controllerbase.MakeGenericType(entityType, datacontextType);
var controller = Activator.CreateInstance(controllerType) as IController;
return controller;
Wiser men than me would use a IOC framework to inject the types, I'm using plain old reflection and reading the type names out of the route values in URLs like:
http://computer/repo/entityname/by/fieldname/value.html
Good luck!

Test-driven development with ASP.NET MVC - where to begin?

I've read a lot about Test-Driven Development (TDD) and I find the principles very compelling, based on personal experience.
At the moment I'm developing a website for a start-up project I'm involved in, and I'd like to try my hand at putting TDD into practice.
So ... I create a blank solution in Visual Studio 2010, add an ASP.NET MVC Website project and a test project.
I also add a class library called 'Domain', for my domain objects, and a test project for that.
Now I'm wondering where to begin. Should I be writing a test before I do anything right? The question is - should I start writing tests for domain objects? If so, what exactly should I be testing for, since the domain objects don't yet exist?
Or should I be starting with the Website project and writing tests for that? If so, what should I write a test for? The Home controller / Index action?
I typically start by collecting a set of stories for the application I'm going to develop. From that I generate a domain model, usually on "paper". I organize the stories that I'm going to implement and start creating the domain model in the DB for the first set of stories.
Once I have the initial DB, then I use an ORM, in my case, LINQ to SQL, to map the DB tables onto a set of initial classes. I don't typically unit test generated code so this gives me a fair amount of code as a base to start with. I then create a stub method, which throws a not implemented exception, to implement one feature of the first domain class I'm working with. Typically, I start with validation logic. Once you have your stub method, then you can use the VS right click menus to create one or more unit tests for that method. Then you're on your way.
Once I've finished with the domain objects for the first story, I then start working with the MVC aspects. First, I'll create the view models for the first view. These are typically just an empty container class as this point. Then I'll create the view and strongly type it to the view model. I'll start fleshing out the view, adding properties to the view model as needed by the view. Note that since the view model is simply a container there aren't typically unit tests associated with it. It will however be used in subsequent controller tests.
Once the view is complete (or at least my initial concept is complete), I then create the stub controller action or actions for it, again the stub method simply throws a not implemented exception. This is enough to get it to compile and let me use the tools to create unit tests for it. I proceed as needed to test the method(s) and ensure that it acts appropriately to the given inputs and produces an appropriate view model. If the method can produce multiple view models, i.e., render multiple views I may iterate over the process of creating view models/views/controller code until the story or stories are complete.
Repeat as necessary until your set of stories are implemented, refactoring along the way.
Writing unit tests before even declaring the class you are testing seems a little extreme in a static languages such as C#. So you start by declaring your domain classes, throw a few interfaces that define operations you will perform on these domain objects and then you add a class that will implement an interface, leaving methods just throw NotImplementedException. At that moment you could write a unit test for this class, as all the types are known. You run the test which will fail, then you implement the method and run the test again - it will pass. Then you could refactor and optimize your implementation, your unit test should still pass.
Once you have a nice domain model and data access layer you could move to the web project where you create controllers, using the interfaces you previously defined (by making a constructor that takes this interface). You write a unit test for this controller by replacing the interface with a mock object, so that you can test the controller actions in isolation from your data access code.
And most importantly: don't be afraid to add classes and interfaces. I've seen people write huge methods that perform multiple things at the same time and which are difficult to test. Try isolating different tasks into methods that you could easily write specifications for: what output you expect for the different possible inputs.
For a long answer you should take small steps like this.
1)-First write a failing test
[Test]
public void AddSameTag()
{
UserMovie userMovie = new UserMovie();
userMovie.AddTag("action", "dts", "dts");
Assert.AreEqual(2, userMovie.Tags.Count);
}
2)- Write simplest code to pass the test.
public virtual void AddTag(params string[] tags)
{
foreach (var text in tags)
{
Tag tag =new Tag(text.Trim());
if (!movieTags.Contains(tag))
movieTags.Add(tag);
}
}
3)- Refactor
.
For ASP.NET MVC and TDD starter you can ignore Controller Test and focus on Domain by TDD.
You can look at ASP.NET MVC 1.0 Test Driven Development

How to write test case for mvc action filters?

I have an action filter which i got from the below link
http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/
there is something called "RequiresAuthenticationAttribute"
for this i need to write test case.
how can i do this? form some of the blogs i read that we need to mock httcontext.
How can i mock this? what is the procedure that i need to do? is there any link for this?
Don't use the [RequiresAuthentication] attribute from Rob's blog. It's meant for a very old pre-release version of MVC. Use the in-box [Authorize] attribute instead.
Since the [Authorize] attribute is written by the MVC team, you don't need to unit test its logic. However, if you want, you can verify that it's applied to your controllers or actions. Simply get the Type or MethodInfo you're interested in, then call its GetCustomAttributes() method to get instances of AuthorizeAttribute. You can inspect those instances for the values that you expect.
If you want, you can look at the source code of AuthorizeAttribute for information on writing your own filter. Additionally, you can look at the official unit test of this type, so if you do end up writing a filter you can use a similar method to write your own type's unit tests.

How to unit test library that relies on Session object

I have several asp.net mvc websites consuming the same controller and model.
This common logic is put in seperate libraries.
These libraries use the HttpContext.Current.Session. How can I make these unit testable?
I read about the StateValue but can't completely grasp it. Where should I get this StateValue thing? Is it a lib I reference?
You can use mock helpers such as seen here
Your code should use IHttpSessionState not HttpSessionState.
If you look up the MSDN documentation for IHttpSessionState you will find an example implementation you can lift into your Unit Test project to create a mock session.
Replace code aquiring the Session with static delegate that return IHttpSessionState.
Initialise that static delegate with a function that uses HttpContext.Current.Session.
During Unit Testing replace delegate with your Mock implementation of IHttpSessionState.
just to channel people out of this sinkhole (which it is as of .NET 3.5) -- don't touch IHttpSessionState for purposes of mocking and testing:
http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/

Resources