What are the next steps for unit testing with dependency injection? - 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.

Related

Is Dependency Injection a must in asp.net MVC?

I am currently viewing multiple tutorials (and reading books) to start working with ASP.NET MVC.
I see that ninject (or similar) is widely used to implement Dependency injection and from what i understood the main issue here is resource allocation from the classes i need.
We want to be sure for example that we have only one instance of the repo object.
I need to learn first things first so i am interested in knowing how i would create an ASP.NET MVC without using DI techniques and still be correct as far as my object resources are concerned
More info:
I have made some winforms applications. These apps where using a Business Layer DLL (BLL). This BLL had access to my DAL DLL (plain ADO.NET). they are working quite well..
No i want to use the SAME BLL to MVC apps.
With injection or not?
Without injection implementation?
Do i just create the BLL object in my controller constructor and that's all?
ASP.NET MVC doesn't require you to use dependency injection at all. It will work perfectly fine if all of your controllers have default constructors. On the other hand, you will be responsible for creating the objects and managing their lifetimes. If you need to have one repository object for the application, you have to manually implement its lifecycle(using a static variable or Singleton pattern).
If you care about testing, using dependency injection will certainly help you to design more testable and reusable objects. You can easily replace the dependencies with test doubles in your test code and let DI container inject the real implementations in the runtime.
If you are sure about not using it, then make sure all of your controllers have default constructors. You don't need any configuration.
Dependency Injection is not a requirement for using ASP.net MVC. You can definitely build an MVC app without it.
Where it will come in handy is if you want to perform unit testing on your application. If you would like to unit test an action in a controller, if you have DI set up, then you can mock your dependencies that are included in the controller constructor (that DI takes care of when the app is running) and set up responses to return when they are called by the Action.
This is much harder and impractical (if not impossible) to do if you are not using Dependency Injection. In such a case, if you want to use Unit Testing, it will be very hard to write pure unit tests of your Actions, since you will have no easy way to mock your service and data access layers for your tests.
And as you wrote, the DI layer will also enable you to ensure things like having only one instance of the repository objects that you are injecting, etc.

Has anyone got a good example of unit of work with multiple repositories that is not using EF?

I am about to implement the unit of work pattern with MVC3.
I have:
MVC Service Layer (BLL)
Repository Layer
Multiple types of databases
I want my service layer to get the IUnitOfWork passed to it by my IOC container. (This is easy and not part of this question).
So my service layer will do this: (Note: this is pseudo code)
(using unitOfWork)
{
ProductSqlRepository.Update();
PersonOracleRepository.Update();
IUnitOfWork.Commit();
}
All the samples I can find use EF. Whilst one of my repositories might use EF others may not.
My question is then, can I use the Unit of work pattern across multiple repositories that may sit above different types of databases (ie... EF, Oracle... other)
So, if I want to wrap an update to a SQL database and an oracle database in the ONE unit of work call, is the unit of work the way to do it.
As I mentioned, all examples I can find are for 100% EF solution, I need to mix and match.
Thanks
RuSs
The UnitOfWork scope is essentially already defined in MVC since all of your logic is done within an action. The common pattern I've seen (and what I ended up doing in my app) is to handle your unit of work via an attribute you register globally to your app and handle setting up whatever unit of work logic (transactions etc) you need to in the OnActionExecuting and OnActionExecuted of that attribute. There are a few caveats like making sure that the action isn't a child action and checking for ModelState errors but there are examples of this online. Also note that if you do not use viewmodels exclusively in your views, you may run into issues with certain frameworks lazy loading data in a view after your unit of work scope has closed.
My project used nHibernate and I used these two posts as inspiration for my implementation. Hopefully they'll give you a few ideas as well.
http://ayende.com/blog/4809/refactoring-toward-frictionless-odorless-code-what-about-transactions
http://slynetblog.blogspot.ca/2011/04/lightweight-nhibernate-and-aspnet-mvc.html

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.

Grails: Services VS Groovy classes

Documentation says:
The Grails team discourages the
embedding of core application logic
inside controllers, as it does not
promote re-use and a clean separation
of concerns.
I have one API controller and a few Groovy classes in src/groovy folder. Those classes just implements my application logic so actions in API controller works in this way:
//index page
def index = {
render new IndexApi().index(params) as JSON
}
I'm curious - is there any reason to move my application logic from plain groovy classes into services ?
Actually services are not just about transactions. Services are great for zero-config injectable singleton components, and they can can be reloaded without restarting the whole grails environment, AND they can be discovered as artefacts and hence automatically exposed with remoting plugins.
If you want transactional behavior you should put your logic in the Services. Else you would have to take care about it yourself, which is not in the spirit of using Grails.
Being not a grails expert myself, I put my 'not transactional' classes outside the service layer, like builder classes, helpers, and other logic that is not transactional but used from the service layer.
There are three reasons:
It makes the controller smaller -> easier to understand and maintain
It makes you logic easier to test.
You really don't want to manage your transactions manually.
If you would put everything in the controller, you would need to create the Web runtime to be able to run any test. If your logic is outside, you can copy the data you need from the HTTP request and all the other sources and just call the code. So the logic isn't depending on HTTP sessions, requests or anything else you don't want to.
For example, to test JSPs, you need a HTTPRequest. For a request, you need a HTTPSession and a JSPWriter. Those need a session context. So just to be able to run a single test, you need to set up and initialize a whole bunch of classes. And all of those are interfaces and the implementations are private. So you must implement the actual methods (all 300 of them) yourself. And you better get this right or your tests won't test what you want.

TDD with ASP.NET MVC 1.0

Where can I find a good tutorial on TDD with ASP.NET MVC 1.0? I'd prefer a video tutorial but a text tutorial would be fine as well. I have a new project starting soon and I want to start off on the right foot.
The Storefront Videos from ASP.NET are a must watch series.
Any tutorial on TDD will be helpful for MVC. I've been doing TDD for sometime and found that it was a natural transition in MVC. There are a few peculiarities that I have found that need to be addressed.
You often need to mock up the HttpContext, which means that you need to assign a ControllerContext to the controller after it's created as that's the only way to inject the mock. The context will be used to provide the Session, Request, and Response objects in the controller (also mock them). New HttpContextBase, HttpSessionStateBase, ... classes make this much easier to do.
Because of (1), invest some time in putting together some helper classes in a separate class library that can be used by all of your test projects. These helper classes should contain methods that provide configurable (or multiple methods to provide specific configurations) of the mocked contexts. This will help keep your tests compact.
Use and assign a ValueProvider for testing methods that accept parameters if you aren't using ModelBinding (with corresponding parameters in the signature) for a controller action. This will allow you to use TryUpdateModel/UpdateModel without adding code to your controller to get data from the Request into those methods.
Use a mocking framework -- if that isn't obvious from above. It will be so much easier to write your tests if you mock out the dependencies. Writing your own mocks, IMO, is not worth it, though I know others don't share that opinion. I guess this isn't unique to MVC, but I thought I'd mention it.
Set up a separate set of tests that use reflection to test that appropriate attributes with appropriate properties are getting set on your methods. MVC makes heavy use of attributes for security and other cross-cutting aspects. These need to be tested as well.
Check out here. MVC store front is highly recommended.
I thought that Rob Conery's 'ASP.NET MVC Storefront Starter Kit' http://www.asp.net/learn/mvc-videos/#MVCStorefrontStarterKit were great for demonstrating TDD with ASP.NET MVC.

Resources