I have a handful of controllers and each controller has a test class with unit tests. Each unit test calls a single action and verifies that the action handles a given scenario.
The test class has a setup routine that instantiates a number of fake repositories and other fake objects. The fake repositories have static collections that the repository methods/functions operate against.
It is working pretty well but I'm running into some challenges:
When entities in one fake collection reference entities in another fake collection the code in the repository's constructor explodes and becomes difficult to manage
When a unit test calls an action that modifies the fake repository data, the static collection changes state making it nearly impossible to operate against that same data in other unit tests
So I have two questions that might require you to also explain your general approach:
How do you go about setting up a fake collection for an entity that references other fake collections/entities?
Do your fake repositories support update/insert/delete operations? If so, how do you prevent changes from one unit test from impacting another unit test?
As long as your repositories are abstracted with interfaces you could use a mock object framework to generate a fake repository and inject it into the controller being tested. Here are some popular choices:
Rhino Mocks
NSubstitute
Moq
With regards to point 2, why not setup the fake repository in the Setup function on your unit test class (which you do) and use the TearDown to reset the state of the repository after each test.
(These are NUnit specific attributes, so I can't comment if other frameworks have the similar features).
Related
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
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.
I'm a grails beginner. and was trying to understand the unit test ..
when i create a domain class Author grails automatically creates a test controller AuthorControllerTests for that domain.
so . in test controller the second line is #Mock(Author)
what does that mean.. what is the advantage i get when i mock a domain class?
as it says in the extensive documentation on testing:
The Mock annotation creates mock version of any collaborators. There is an in-memory implementation of GORM that will simulate most interactions with the GORM API. For those interactions that are not automatically mocked you can use the built in support for defining mocks and stubs programmatically.
Also AuthorControllerTests are the tests for the AuthorController, not the Author domain class.
Just to add something, mocking is useful when you need to isolate a "unit" of code like here your controller.
By isolating, we mean write simple components to replate and simulate all dependancies. This simple components are what we call Mocks.
Grails here gives you the possibility to mock the domain class which will make your tests easier as it won't store the information in the database.
If you want to test the whole stack, from the controller to the database, it's what we call an integration test.
hope it helps
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.
We are building an ASP.NET MVC site, and I'm struggling with where to define a connection to best enable unit testing (I use 'connection' generically - it could be a session, a connection, an adapter, or any other type of data context that can manage transactions and database operations).
Let's say we have 3 classes:
UserController
UserService
UserRepository
In the past, we'd do something like this within a method of the UserService:
Using (ISomeSession session = new SomeSession())
{
session.StartTransaction();
IUserRepository rep = new UserRepository(session);
rep.DoSomething();
rep.Save();
session.Commit();
}
However, it wasn't really possible to unit test this since the dependency on SomeSession wasn't injected. However, if we use D.I. to inject the dependency in the UserService, the session hangs around for the life of the UserService. If there are multiple services called from the UserController, each could have sessions just hanging around until the UserController is garbage collected.
Any thoughts on how to better manage this? Am I missing something obvious?
Edit
Sorry if I wasn't clear - I understand that I can use Dependency Injection with the Session/Data Context, but then it's being maintained over the life of the Service class. For any longer-running actions/methods (i.e. let's say the service is being called by a batch process), this could lead to a lot of open sessions for no reason other than adding testability.
As RichardOD correctly observed, you can't use live database connections for writing unit tests. If you are doing it, then you are integration testing.
I have separate implementations for my repository interface, one real repository, and one fake repository for unit testing. The fake repository works on a generic list instead of a real data context. I am using DI (with Ninject to make things more comfortable, but you can do it just as well by hand) to inject the correct repository.
There are only very few instances in which I am unit testing with real connections, but that's a unit test for my repository class, not for any controller, UI or Business layer objects.
Edit: With the comment you added, I think I now understand what you were actually asking for. Funny you'd ask something about that, since I worked on the very same subject last week :-)
I instantiate the data context inside a very thin wrapper and put the context inside the HttpContext.Current.Items dictionary. This way, the context is global, but only for the current request.
Still, your question's subject is highly misleading. You were asking "where to instantiate a data context for unit testing" and the answer is that you usually don't. My unit tests still operate on fake repositories.
The easiest way is to have a Connectionstring that you define in web.config for development and production. For Unittests you define it in app.config of your Testproject.