Unit testing an ASP.NET MVC 3 application - asp.net-mvc

We have an ASP.NET WebForms application that we're going to convert to be ASP.NET MVC application - one of the reasons is so that we may take full advantage of Unit Testing and TDD.
Our current WebForms application makes heavy use of HttpModules. We're currently debating whether we should stick with HttpModules or use Global Filters (any advice here would be great).
However, with my few "hello world" test MVC applications, I've not worked out how to get the HttpModule (or indeed the Global Filter) code to fire when Unit testing.
Maybe I'm wrong, but it seems to me that I need this to be part of my unit-testing (integration testing) otherwise it can't be a true representation of what's going on in my Production code.
Any guidance would be most welcome.
Thanks
Griff
PS - I added the following after the initial responses to my question.
Simple made-up Use Case
In Production
Browser makes a Request for a Controller Method
HttpModule fires (or Global Filter) - this sets a static Guid property to have a value.
The controller method takes this Guid value and uses it in its subsequent logic
Correct result is then returned to the browser
In Unit Testing
Unit test calls the same Controller Method
The HttpModule (or Global Filter) does not fire - the static Guid property has a value of Guid.Empty
The controller method takes this Guid value, but throws an error because it was an Empty Guid
Unit test fails
My thoughts are:
if a Controller relies upon an HttpModule (or Global Filter) to run first, then the HttpModule is a dependency and therefore the results of it's action must be Stubbed for the test to be a true Unit Test.
If the test is to include the effect of the HttpModule (or Global Filter) to run, then this would be an Integration test (though it's still not clear yet how to get the HttpModule or Global Filter to run as part of the Integration test)
The HttpModule (or Global Filter) should have their own set of Unit Tests
I think this is the approach I'll take, but if anyone could suggest how I get my Integration test (as described above) to work then I'd be most grateful.
The problem as I see it is that my TEST project becomes the "start up" project when running my tests, so the HttpModules (defined in the ASP.NET MVC's web.config file) and the Global Filters (defined in the ASP.NET MVC's global.asax file) will not run because the web.config and global.asax files are not executed. So the question remains: how do I get these to run in my Integration test?
Thanks everyone
Griff

You shouldn't be testing to check if the global filter fires or not. The mechanism that fires the code isn't your code, it's part of the framework so the framework team is supposed to test that.
Instead you should simply be testing to make sure that the global filter has been applied.

Whether or not to call a HttpModule or Global Filter is handled by the Framework. You shouldn't be worried about Unit Testing things that are handled by the Framework. Your Unit Tests should only test that your HttpModule or Global Filter behave properly when called.

I would mock the http modules and repositories to unit test the controllers and services, in my view that's how you unit test. the global filters and httpmodules you can test it with end to end tests. Hope it helps.

Related

UI Testing MVC with WatiN and injecting parameter to controller

First off, I may be barking up the wrong tree with this, so please correct me if I am wrong.
That said, I am trying to write sme UI unit tests that use WatIn. I am only working on a subset of the UI at present.
I have a controller called Product along with its associated views.
the Controller takes in a ProductRepository via the constructor.
What I would lie to do is to test that different product categories are rendered correctly, in different tests, so I need to pass in some kind of stubbed or mocked repository into my code.
My test is set up along the lines of;
using (var ie = new IE("http://localhost:2904/Product"))
{
...
}
So how do I pass in a repository to my controller that will provide the appropriate product? Once I have called the using statement, my system has launched the browser, so that is too late. But until the browser is launched, then the controller doesnt exist, so I can't inject in the appropriate repository.
Or have I fundamentally got this wrong, and I can only use WatiN against my database, and I need to program it to select a member of each type of product from the db, adn test that way?
I think, as you suggesting, you pick the wrong end of the problem. If I understand correctly, you don't need UI test and Watin but rather integration tests. I would suggest to create instance of controller, inject repositories as needed and mock other dependencies. Than you can switch repositories and so.
In UI tests you test your whole application from the top of UI down to database so it's hard to change behavior or mock some parts. Do you really need to test your functionality with UI? Wouldn't be better to test it only in controller or it's not option for your case?
Seems ok or I misunderstand you completely?

Unit testing Asp.Net MVC routes: which approach to choose?

I'm new Asp.Net MVC and unit testing, so I apologize in advance if questions are somewhat stupid
When unit testing incoming routes, we must feed an URL into the routing system and verify that this URL is processed correctly.
1) But should the routes be tested separately ( thus a particular unit test would test no more than one route ) or should all routes be tested as a whole ( ie each unit test would test an instance returned by RouteCollection.GetRouteData(...); ) or both?
2) If the answer to 1) is that routes should be tested as a whole, then I have trouble understanding how many URLs would we need to pass into the routing system to be sure it works correctly:
a) as far as I can tell, wouldn't we need to pass at least as many as many URLs as there are registered routes, where each of these URLs should be processed by a different route ( this way all routes would get the chance to process one URL )?
b) Should all URLs be tested within a single unit test or should we have one unit test for each url? If the latter, then wouldn't the number of unit tests be the same as if each unit test would test no more than a single route?
c) Assuming we add a new route to the routing system, then we will most likely also need to modify existing unit tests in order for them to continue working properly, while if instead we were testing routes separately, then no modification of existing unit tests would be necessary?
thank you
You should be careful with these kinds of test as you could easily end up testing the Asp.Net MVC code, which is something that Microsoft presumably does. (For example: wouldn't these tests be testing the functionality of the GetRouteData method?)
Unless I'm misunderstanding you, it sounds like you just want to make sure you're configuring the route data correctly.
I would consider this type of configuration code to be simply part of creating your application's object graph, and not subject to unit testing. There are several reasons for this:
The configuration probably takes place in the composition root (e.g., within Application_Start in global.asax).
Any configuration initializes the system to a "technically correct" state. (Like if you replaced a production component with a test double. The system works; it just needs to be configured differently for production.)
It's very likely for these configurations to change in the future. For example, you mentioned that new routes could be added later. It's possible that existing routes may be changed, as well.
End-to-end/Smoke testing will make sure the application doesn't return a 404, which is usually what happens if the routing data is not configured properly.
After considering this, if you remain undeterred in testing the configuration then consider creating an abstraction that handles this configuration. That is, create a seam at the boundary where you are registering these routes.
This would allow you to mock out the calls to the Asp.Net MVC framework, and verify that you are sending it the expected configuration.

What are the next steps for unit testing with dependency injection?

I'll start out by saying I'm a huge fan of unit testing. I've been using it for a couple of years. So far, though, my use has been limited to ensuring engineering calculations are performed correctly, strings are formatted properly, etc. Basically, testing my work on class libraries to be consumed in other projects.
Now, I want to branch out and apply unit testing to my work on ASP.NET Web API. At this point I have my controller written and working with Ninject. Although I'm using Ninject, I'm still not 100% sure why I'm doing it and haven't seen the benefits yet.
On to my question, what are the next steps for unit testing my Web API controllers? What should I do next and when will I reap the benefit of using Ninject?
Next, you could create fake data (or a mock) that your controller can return to your views. This will allow you to do front end development without having to complete the back end implementation.
The benefit of using Ninject is that you can create mock objects for testing purposes. By injecting the interface instead of the concrete implementation you can easily switch between the real and mock object. To do this you simply change which one should be injected in the Ninject bindings. Using something like Rhino Mock in conjunction with Ninject you can write and test your code (controllers, views, etc) without having to fully implement all of the functionality. When you're ready to implement a mocked piece of functionality, you don't have to rewrite your code to accommodate the changes, you simply update your bindings. Now real data will display on your pages instead of the mocked data you created previously.

Mocking a Controller dependency with Moq using specflow

I am new to specflow and a have a doubt about how to mock my
controller dependencies.
For instance I have a UserController class which depends on my
UserRepository class that a pass to the controller class on its
constructor.
So using Moq I am doing something like this:
var mock = new Mock<UserRepository>();
mock.Setup(m => m.ListAll()).Returns(new List<User>());
var browser = new IE(string.Format("http://localhost:4265/{0}",
username));
But my controller is not using the mocked object, how should I do
that?
Thanks
You are mixing three (atleast) test framework, which ofcourse is cool, but you should probably stop and consider what it is you want to test.
Watin is good for testing your UI as it controls a browser instance. I find it good at making regression tests http://en.wikipedia.org/wiki/Regression_testing
Specflow is great as well - personally i like to use it for closing the gap between business developers and (us) software developers as we can actually define requirements in terms we both understand (and probably other parts of the organization as well) I don't want to start a flame war, but it can introduce more problems than it solves, unless you focus on its real values. We use this at work by testing the service layer (one layer below the controllers in the presentation layer) and we actually only mock the database, external services and file system etc - which makes our specflow tests some kind of integration tests.
Moq is a mocking framework and can ofcourse be used in any kind of tests (like i just let it slip we do) but this is such a great tool for unit testing.
So to return to your question. If you want to make one test to find all your bugs, you're in trouble ;) I know you don't want that - that was just a silly suggestion i made - but really, if you just want to do integration tests (tests running from the UI down through several layers/dependencies) you could easily mix different testing frameworks like you are now, but then why mock the user repository? Is that because you don't want to hit the database?
Anyways one way to do the integration test you seem like you want would be to configure your solution to use a mock - or perhaps a stub would do (create a fake userrepository that returns the data you want to test with) - you should use a Dependency framework like Unity, Ninject or structure map (boy let's not start a war about what framework to use) and have the test url Watin is using launch your site using a configuration with the fake/mock repositories.
You could on the other hand do unit testing on your controllers, services etc. You might even want to try out TDD but that's a whole other chapter i can't cover here!
You are not doing anything with the mock to inject it into your controller. Your controller needs to be given the user repository in order for it to be used.
Also you need to accept more answers.

What's the best practice to setup testing for ASP.Net MVC? What to use/process/etc?

i'm trying to learn how to properly setup testing for an ASP.Net MVC.
and from what i've been reading here and there thus far, the definition of legacy code kind of piques my interests, where it mentions that legacy codes are any codes without unit tests.
so i did my project in a hurry not having the time to properly setup unit tests for the app and i'm still learning how to properly do TDD and unit testing at the same time. then i came upon selenium IDE/RC and was using it to test on the browser end.
it was during that time too that i came upon the concept of integration testing, so from my understanding it seems that unit testing should be done to define the test and basic assumptions of each function, and if the function is dependent on something else, that something else needs to be mocked so that the tests is always singular and can be run fast.
Questions:
so am i right to say that the
project should have started with
unit test with proper mocks using
something like rhino mocks.
then anything else which requires
3rd party dll, database data access
etc to be done via integration
testing using selenium?
because i have a function which
calls a third party dll, i'm not
sure whether to write a unit test in
nunit to just instantiate the object
and pass it some dummy data which
breaks the mocking part to test it
or just cover that part in my
selenium integration testing when i
submit my forms and call the dll.
and for user acceptance tests, is it
safe to say we can just use selenium
again?
Am i missing something or is there a
better way/framework?
i'm trying to put in more tests for regression testing, and to ensure that nothing breaks when we put in new features. i also like the idea of TDD because it helps to better define the function, sort of like a meta documentation.
thanks!!
hope this question isn't too subjective because i need it for my case.
so am i right to say that the project should have started with unit
test with proper mocks using something
like rhino mocks.
The project should have started with a good separation of concerns. Once you have a good separation and you work with abstractions instead of concrete classes using a mocking framework and writing unit tests is a piece of cake.
then anything else which requires 3rd
party dll, database data access etc to
be done via integration testing using
selenium?
Yes.
because i have a function which calls
a third party dll, i'm not sure
whether to write a unit test in nunit
to just instantiate the object and
pass it some dummy data which breaks
the mocking part to test it or just
cover that part in my selenium
integration testing when i submit my
forms and call the dll.
You should not have a function that calls a third party DLL. You should write an abstraction/wrapper around this DLL which you would use and which will be mocked in the unit test where you will verify that your function calls the proper methods without really calling it. You would then use a DI framework in the application to do the plumbing.
and for user acceptance tests, is it
safe to say we can just use selenium
again?
Selenium or any other Web testing framework would be fine. In the more advanced ($) versions of Visual Studio you could write web tests.

Resources