Mocking without injection - c#

(C#, WCF Service, Rhino Mocks, MbUNit)
I have been writing tests for code already in place (yes I know its the wrong way around but that's how its worked out on my current contract). I've done quite a bit of re-factoring to support mocking - injecting dependencies, adding additional interfaces etc - all of which have improved the design. Generally my testing experience has been going well (exposing fragility and improving decoupling). For any object I have been creating the dependant mocks and this sits well with me and makes sense.
The app essentially has 4 physical layers. The database, a repository layer for data access, a WCF service that is connected to the repository via a management (or business logic) layer, so top down it looks like this;
WCF
Managers
Repository
Database
Testing the managers and repository layer has been simple enough, mocking the dependencies with Rhino Mocks and injecting them into the layer under test as such.
My problem is in testing the top WCF layer. As my service doesn't have the constructor to allow me inject the dependencies, I'm not sure how I go about mocking a dependency when testing the public methods (ServiceContracts) on the service.
I hope that's made sense and any help greatly appreciated. I am aware of TypeMockIsolator etc, but really don't want to go down that route both for budget and other reasons I won't go into here. Besides I'm sure there are plenty of clever 'Stackers' who have the info I need.
Thanks in advance.

Is there a specific reason you cant have a constructor on your service?
If not, you can have overloaded constructors with a default constructor wiring up the defaults and one parametrized constructor with your dependencies. You can now test the parametrized ctor and rely on the default ctor for creating the instance in production.
public MyService() : this(new DefaultDep1(), new DefaultDep2())
{
}
public MyService(IDep1 d1, IDep2 d2)
{
}
A better solution if you use dependency injection would be to use the WCF IInstanceProvider interface to create your service instance and provide the needed dependencies via that injection point. An example using Structure Map can be found here.

You could make the WCF services a thin layer over the 'managers', so they have little or no logic in them which needs testing. Then don't test them and just test the managers. Alternatively, you could achieve a similar effect by having another 'service' layer which contains the logic from the services, which can be tested, and make the actual WCF code just pass through to that.

Our WCF service gets all its dependencies from a Factory object, and we give the service a constructor which takes IFactory. So if we want to write a test which mocks one of the dependencies, say an IDependency, we only need to inject a mock factory, which is programmed to give mocked IDependency object back to the service.

If your using an inversion of control (IoC), such as Unity, AutoFac or Castle Windsor, and a mocking framework (eg. Moq, NMock, RhinoMocks) this is simple enough as long as you have the right design.
For a good tutorial on how to do it with RhinoMock and Windsor, take a look at this blog article - http://ayende.com/Blog/archive/2007/02/10/WCF-Mocking-and-IoC-Oh-MY.aspx

If you're using Castle Windsor, take a look at the WCF facility, it lets you use non-default constructor and inject dependencies into your services, among other things.

Related

Can ninject be used to configure class based inject (instead of interface)?

Can Ninject be used to configure non-interfaced based injection?
public EntityController([Named("EntityServiceName")] EntityService service)
instead of
public EntityController([Named("EntityServiceName")] IEntityService service)
I'm trying to do just this and running into problems, and was wondering if the issue was that I'm not using interfaces.
Additional info:
Maybe I'm off here, but here is the benefit we're hoping for:
We're following a DDD pattern with an onion/ports and adapters architecture, so we have a domain project with concrete domain objects and domain services as well as external interfaces defined, an infrastructure project which implements the external interfaces defined in the domain, and finally a web api project for exposing them.
The controllers of the web api need to have an instance of the domain services injected into them. But since there would be a 1:1 relationship between the interface and the domain service, it seems like unnecessary bloat to just add interfaces for the domain services.
So there is really no benefit to making an interface for the domain services, but I would still like to configure and inject them via Ninject.
You can... yes. But there's not much it accomplishes. Here's an example:
kernel.Bind<List<string>>().ToConstant(new List<string>(){"Foo", "Bar"});
But if you're not using an Interface, you're not really getting much benefit of Dependency Injection. And obviously this accomplishes nothing over ICollection. I suppose you could use it to set default class values, and still get the advantage of unit testing... but doing so with Interfaces will usually be much better, since you can do much better mocking. I would only do this for the most basic of classes.

Mocks for service using spring.net for IoC

I'm in the process of creating unit tests for an existing serie of classes that use spring.net IApplicationContext to resolve types and I want to mock the dependencies resolved by spring.net.
I'm having problems getting spring.net to use my mocked objects, basically getting ContextRegistry.GetContext() to return them in the actual application.
The best solution I've found so far is something similar to this, but is not very clean to manage in the actual unit test code, or defining my own IApplicationContext on the fly and register it in the registry which has the same problem.
My question is whether I'm missing some framework that ties these things together or some pattern I can use that would allow me to define things easily.
Your classes are using IApplicationContext as a service locator. Many consider "Service Locator" an anti-pattern. I suggest you form your own opinion on this; if you agree that it is an anti-pattern, then you can take this opportunity to factor out the dependency on IApplicationContext and replace them by explicit dependencies on the objects your class needs.
If you (have to) stick to the current approach, then I'm afraid it's really difficult to get a clean solution. In your situation, I'd configure my containers specifically for testing (perhaps including mocks like described in your linked blog post) and use Spring.net unit test support for easy wiring of my test objects. But I'd feel really uncomfortable - like you ...

Injecting Mocks on large dependency object graph

I have a a fairly significant dependency graph for an object I want to test. What is the easiest way to resolve my dependencies without having to register mocks everywhere?
For example, I have a dependency graph like this:
PublicApi
ApiService
AccountingFacade
BillingService
BillingValidation
BillingRepository
UserService
UserRepository
I want to test PublicApi.CreateUser(), and I want it to run through all the code, but I want to mock the repositories so I don't have to write anything to the database. Should I just use a DI container and register all my services, replacing the repositories with mocks, then resolve PublicApi and run the method?
I was looking into AutoFixture, and it looks like it might be able to handle something like this, but I can't quite wrap my head around the whole 'Freeze' vs 'Register' and it's integration with Moq.
For Unittests you should only mock the direct dependencies. In your case you create PublicApi and inject a mock for ApiService and verify if PublicApi is calling the appropriate methods with the correct values on the ApiService Mock.
The same way you test all the other components isolated from the deeper dependencies.
If you want to test the combination of several components, that isn't unit testing but rather integration testing. Therefore it depends of how you are putting your classes together. e.g. if you are using an IoC container, it probably supports replacing the configuration for the repositories in some way. In this case you can use the configuration of the application and replace the repositories and potentially also the views with mocks.
This may not be helpful in the least but I will say it anyway.
It seems you are trying to test too much at once, why not just test BillingService -> BillingValidation, then BillingService -> BillingRepository etc. This way you would have a suite of tests proving that each one works, then when you are up at the PublicApi Layer you only need to mock ApiService, as you have already tested everything beneath it, so there is no value in testing it again.
Generally I will only test 1 layer at a time, but I dont know your full scenario so you may have something which I am not accounting for, so if this is the case and you REALLY need to test all of this together I would just bring in a simple and lightweight DI framework like Ninject or something.
This way you can just bind all your types to mocks, then instanciate your PublicApi from it.
With ninject it would look something like:
Kernel.Bind<UserRepository>.ToConst(YourMockUserRepositoryInstance);
Kernel.Bind<UserService>.ToConst(YourMockUserServiceInstance);
Kernel.Bind<BillingRepository>.ToConst(YourMockBillingRepositoryInstance);
Kernel.Bind<BillingValidation>.ToConst(YourMockBillingValidationInstance);
Kernel.Bind<BillingService>.ToConst(YourMockBillingServiceInstance);
Kernel.Bind<AccountingFacade>.ToConst(YourMockAccountingFacadeInstance);
Kernel.Bind<ApiService>.ToConst(YourMockApiServiceInstance);
Kernel.Bind<PublicApi>.ToSelf();
var publicApi = Kernel.Get<PublicApi>();
Although you have to ask yourself, what are you testing here? if its just interactions I would do as I first mention, if its more then maybe think about the latter choice. Either way I hope it gives you some options.

Dependency Inject exposition and DependencyResolver in ASP.NET MVC 3?

I have a service (AccountService) which has around eight methods. One of these methods sends an email. I have another service (EmailService) which is constructor injected into the AccountService.
I was wondering whether it's necessary to do this because it feels like every time I add functionality with a dependency to a method I have to change all my tests where I'm mocking up the dependencies for the constructor. This feels like DI is actually making it harder to change things, rather than easier.
So I was thinking about using the DependencyResolver in my controller action which calls the AccountService to get hold of the EmailService and pass it in. However, will this affect my tests?
How would I go about testing the controller action that used the dependency resolver? Given that the account service is constructor injected by ninject into the AccountController.
Cheers.
Don't use the DependencyResolver in your Controller! Just use it to create the controller using Ninject (See https://github.com/ninject/ninject.web.mvc/wiki). Everything else should be created by Ninject using constructor injection.
Actually, Unit Testing with proper DI and a design that follows the SOLID principles is quite easy.
In the test fixture setup you do nothing else than creating a (dynamic) mock for each dependency and an instance of the object under test using the created mocks as dependencies. That way you have to call the constructor exactly once for all your tests for each class.
If testing is hard it's not because of DI but rather by either not following the SOLID principles (most likely the single responsibility principle) or because of bad tests e.g. Unittests that use real instances of dependencies rather than mocks or doing too much in your test fixture setup.
Have you considered using the Property DI or is it necessary to inject it into the .ctor?
BTW:for your tests are you using somekind of Mocking Framework (e.g. Moq, RhinoMocks)?
Hope it will help you.

StructureMap DI on Model Assembly

I’m new to Dependency Injection and had a question/need guidance.
I had an application that used the repository pattern for data access. I used StructureMap to get the correct repository and all worked well.
I have since broken out my model (including the repository logic) into its own assembly and added a service layer. In the interest of DI the service layer class takes an IRepository in its constructor. This seems wrong to me as now all consumers of my model need to know about the repository (at least configure their DI to know which one to use). I feel like that is getting into the guts of the model.
What sounds wrong with this?
An application written to use dependency injection typically configures a single container instance where all the interface/implementation type mappings have been registered at an initialization stage of the application. This would include the registration of the repositories, services, and any consumers of the service within the application.
By resolving the consumers of the service through the container, consumers need only indicate their dependency upon the service, not any dependencies the service might need. Therefore, the consumers of the service will not be coupled to its dependencies (e.g. your repository). This is the benefit of doing dependency injection through a container as opposed to doing manual dependency injection.
If you are designing services to be consumed by other applications in the form of a reusable library then your options will vary depending on the level of flexibility you wish to offer.
If you presume all clients of your library will be using dependency injection, then you will need to provide an appropriate amount of documentation about what types need to be registered within their container.
If you presume all clients will be using a specific container (e.g. StructureMap), then you can ease the registration requirements by providing registries which encapsulate all the specific registration needs for the client.
If you wish to allow your library to be used by clients not using their own dependency injection container then you can provide a static factory which returns the service. Depending on the level of complexity, such a scenario may not require use of a container (for example, if your service is comprised by just a few objects in all). If your library is comprised of a substantial amount of components which need to be composed then you might have factories which resolve the services through their own shared internal infrastructure initialization needs.
I understand your dilemma there Dan, I too spent lots of time wrestling over that in my mind. I believe the way I decided to go forward with was one of best ways to encapsulate all of the concerns and still have easily maintainable loosely coupled objects.
I wrote this blog post specifically about NHiberante but if you look at the repository pattern in implement you can easily change the NH specific code to use your backingstore.
Creating a common generic and extensible NHiberate Repository

Categories