How to UnitTest System.Web.Mvc.Html.InputExtensions.TextBoxFor? - asp.net-mvc

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

Related

ways of using ninject properly

One of the definition of ninject in internet is;
"Somewhere in the middle of your application, you're creating a class
inside another class. That means you're creating a dependency.
Dependency Injection is about passing in those dependencies, usually
through the constructor, instead of embedding them."
what i want to learn is, where ever we see a creation of a class inside another class should we use ninject or just we should use in some part of program that we want/need to apply loosely coupling for design purposes because maybe we would like to use different approaches in the future?
Sorry if this is a silly question.
It's a perfectly valid question, and there are no absolute right or wrong answers. Ninject and other IoC frameworks are designed to de-couple dependencies.
So the moment you do this:
public class MyClass1
{
public MyClass1()
{
MyClass2 mc2 = new MyClass2();
}
}
You can categorically say that MyClass1 has a dependency in MyClass2.
For me, my rule is this: do I need to unit test MyClass1, or is it likely I'll need to unit test MyClass1?
If I don't need to unit test it, then I don't find much value in decoupling the two classes.
However, if I do need to unit test MyClass1, then injecting in MyClass2 gives you much better control over your unit tests (and allows you to test MyClass1 in isolation).
You do need to evaluate each case separately though. In the above example, if I need to unit test MyClass1, and MyClass2 is just a basic string formatting class, then I probably wouldn't decouple it. However, if MyClass2 was an email sending class then I would de-couple it. I don't want my unit tests actually sending emails, so I would feed in a fake for my tests instead.
So I don't believe there are any solid rules, but hopefully the above gives you a better idea of when you might decouple, and when you might not decouple.

Is it really necessary to test controller methods?

When I design MVC apps, I typcially try to keep almost all logic (as much as possible) out of my app. I try to abstact this into a service layer which interfaces with my repositories and domain entities.
So, my controller methods end up looking something like this:
public ActionResult Index(int id)
{
return View(Mapper.Map<User, UserModel>(_userService.GetUser(id)));
}
So assuming that I have good coverage testing my services, and my action methods are simple like the above example, is it overkill to unit test these controller methods?
If you do build unit tests for methods that look like this, what value are you getting from your tests?
If you do build unit tests for methods that look like this, what value
are you getting from your tests?
You can have unit tests that assert:
That the GetUser method of the _userService was invoked, passing the same int that was passed to the controller.
That the result returned was a ViewResult, instead of a PartialViewResult or something else.
That the result's model is a UserModel instance, not a User instance (which is what gets returned from the service).
Unit tests are as much a help in refactoring as asserting the correctness of the application. Helps you ensure that the results remain the same even after you change the code.
For example, say you had a change come in that the action should return a PartialView or JsonResult when the request is async/ajax. It wouldn't be much code to change in the controller, but your unit tests would probably fail as soon as you changed the code, because it's likely that you didn't mock the controller's context to indicate whether or not the request is ajax. So this then tells you to expand on your unit tests to maintain the assertions of correctness.
Definitely value added IMO for 3 very simple methods which shouldn't take you longer than a couple of minutes each to write.

MVC 3: How to Mock an instance of WebViewPage<T>?

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

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.

Resources