I'm utilizing the Reporting Services web service to generate a report and allow the user to download it. This is occuring via PDF, Excel, XML, etc. and working just fine. I'm trying to create some seperation between my reporting class and the implementation, but am struggling with how I can can do this in a manor that is still testable.
Since my custom Reports Object/Class is calling the web service directly, should I seperate this out even further with the use of interfaces? Any reccomendations on this and how it would still be unit testable regardless of the byte source would be much appreciated.
Russell, I think your answer lies in learning about Dependency Injection/Inversion of Control. You might start here...
http://codebetter.com/blogs/jeremy.miller/archive/2005/10/06/132825.aspx
http://misko.hevery.com/2009/01/14/when-to-use-dependency-injection/
http://iridescence.no/post/Using-Unit-Tests-to-Uncover-Design-Flaws.aspx
http://en.wikipedia.org/wiki/Dependency_injection
http://martinfowler.com/articles/injection.html
If you're new to Dependency Injection/Inversion of Control, this link is a great screencast by Carl Franklin and James Kovacs.
DNR TV Show #126: James Kovacs' roll-your-own IoC container
I'm a sucker for learning new things by hearing others explain it clearly and watching them code it. James explains the principles, the code that does it, and how you can further your study by using a framework.
As mentioned, Dependency Injection/Inversion of Control is the way to go. Code to an interface rather than a concrete class. Then, when your unit test runs it can swap the web service implementation with a mock implementation that returns fake, fixed data.
Related
I'm slightly new to Unity and IoC, but not to MVC. I've been reading and reading about using Unity with MVC and the only really useful thing I'm consistently seeing is the ability to get free DI with the controllers.
To go from this:
public HomeController() : this(new UserRepository())
{
}
public HomeController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
To this:
public HomeController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
Basically, allowing me to drop the no parameter constructor. This is great and all and I'm going to implement this for sure, but it doesn't seem like it's anything really that great for all the hype about IoC libraries. Going the way of using Unity as a service locator sounds compelling, but many would argue it's an anti pattern.
So my question is, with service locating out of the question and some DI opportunities with Views and Filters, is there anything else I gain from using Unity? I just want to make sure I'm not missing something wonderful like free DI support for all class constructors.
EDIT:
I understand the testability purpose behind using Unity DI with MVC controllers. But all I would have to do is add that one extra little constructor, nix Unity, and I could UnitTest just the same. Where is the great benefit in registering your repository types and having a custom controller factory when the alternative is simpler? The alternative being native DI. I guess I'm really wondering what is so great about Unity (or any IoC library) besides Service Locating which is bad. Is free Controller DI really the ONLY thing I get from Unity?
A good IoC container not only creates the concrete class for you, it examines the couplings between that type and other types. If there are additional dependencies, it resolves them and creates instances of all of the classes that are required.
You can do fancy things like conditional binding. Here's an example using Ninject (my preferred IoC):
ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
ninjectKernel.Bind<IValueCalculator>().To<IterativeValueCalculator().WhenInjectedInto<LimitShoppingCart>();
What ninject is doing here is creating an instance of IterativeValueCalculator when injecting into LimitShoppingCart and an instance of LinqValueCalulator for any other injection.
Greatest benefit is separation of concern (decoupling) and testability.
Regarding why Service Locator is considered bad(by some guys) you can read this blog-post by Mark Seeman.
Answering on your question What is so good in Unity I can say that apart from all the testability, loosely-coupling and other blah-blah-blah-s everyone is talking about you can use such awesome feature like Unity's Interception which allows to do some AOP-like things. I've used it in some of last projects and liked it pretty much. Strongly recommended!
p.s. Seems like Castle Windsor DI container has similar feature as well(called Interceptors). Other containers - not sure.
Besides testing (which is a huge benefit and should not be under estimated), dependency injection allows:
Maintainability: The ability to alter the behavior of your code with a single change.
If you decide to change the class that retrieves your users across all your controllers/services etc. without dependency injection, you need to update each and every constructor plus any other random new instances that are being created, provided you remember where each one lives. DI allows you to change one definition that is then used across all implementations.
Scope: With a single line of code you can alter your implementation to create a singleton, a class that is only created on each new web request or on each new thread
Readability: The use of dependency injection means that all your concrete classes are defined in one place. As a developer coming onto a project, I can quickly and easily see exactly which concrete classes are mapped to which interfaces and know that there are no hidden implemetations. It means I can not only read the code better but empowers me to have the confidence to develop against the code
Design: I believe using dependency injection helps create well designed code. You automatically code to interfaces, your code becomes cleaner because you haven't got strange blocks of code to help you test
And let's no forget...
Testing: Testing is huge! Dependency injection allows you to test your code without having to write code specifically for tests. Ok, you can create a new constructor, but what is stop anyone else using that constructor for a purpose it has not been intended for. What if another developer comes along six months later and adds production logic to your 'test' constructor. Ok, so you can make it internal but this can still be used by production code. Why give them the option.
My experience with IoC frameworks has been largely around Ninject. As such, the above is based on what I know of Ninject, however the same principles should remain the same across other frameworks.
No the main point is that you then have a mapping somewhere that specifies the concrete type of IUserRepository. And the reason that you might like that is that you can then create a UnitTest that specifies a mocked version of IUserRepository and execute your tests without changing anything in your controller.
Testability mostly, but id suggest looking at Ninject, it plays well with MVC. To get the full benefits of IOC you should really be combining this with Moq or a similar mocking framework.
Besides the testability, I think you can also add the extensibility as one of the advantages. One of the best practices of Software Development is "working with abstractions, not with implementations" and, while you can do it in several ways, Unity provides a very extensible and easy way to achieve this. By using this, you will be creating abstractions that will define the contracts that your component must comply. Say that you want to change totally the Repository that your application currently uses. With DI you just "swap" the component without the need of changing a single line of code on your application. If you are using hard references, you might need to change and recompile your application because of a component that is external to it (In a different layer)
So, bottom line, IMHO, using DI helps you to have pluggable components in your application and have a SOLID application design
I've got some code which downloads some RSS feeds.
I've been using WebClient or Argotic.Syndication.RssFeed libraries.
But these aren't mockable :(
I definately do not want to hit the real RSS feed every time I run the unit test.
Does anyone have any suggestions to what I can do?
Do I need to create an evil wrapper? If so .. suggestions on this?
Does anyone have any suggestions to what I can do?
Abstract the actual HTTP call behind an interface. Then write an implmentation of this interface using WebClient. Now have your main class take this interface as dependency. You could now mock this interface in the unit test and configure your dependency injection framework inject the correct implementation at runtime.
I go for creating a wrapper for every external dependency (if it's practical). So, every interaction with the filesystem/a webservice/database should be done through an interface only, which will lead to more testable code.
Another solution of course is (as always) Typemock Isolator.
I was reading about DI thoroughly, and it seems interesting. So far, I'm totally living without it.
All the examples i saw are related to JNDI and how DI helps you being more flexible.
What is real life applications/problems that you solved with DI that will be hard to solve in other ways?
UPDATE
All the answers till now are educating, but to rephrase the question, I'm looking for examples in your programming life, that made you say "this problem will be best solved with a DI framework".
Just the other day, I decided to read up on dependency injection. Until then, I only knew the word. Honestly, my reaction to Martin Fowler's article was, "That's it?"
I have to agree with James Shore:
"Dependency Injection" is a 25-dollar term for a 5-cent concept.
That doesn't mean at all that it's a bad concept. But seriously, when an instance A needs to work with another instance B, it comes down to these choices:
let A find B:
That means B must be global. Evil.
let A create B:
Fine, if only A needs B. As soon as C also needs B, replace A by C in this list. Note that a test case would be a C, so if you do want to test, this choice is gone as well.
give B to A:
That's dependency injection.
Am I missing something? (Note that I'm from the Python world, so maybe there are language specific points I'm not seeing.)
Yesterday I found a mobile on the bus. The person who lost it had no clue about the person possessing her mobile. I called her dad and told him I have the mobile of his daughter. So I injected the dependency from me into him. Typically a case of the hollywood principle "Don't call us (because you can't!), we call you". Later he came and picked up his daughters phone.
I'd call that a real world problem which I solved by dependency injection, isn't it?
In my opinion, DI is not THE way to solve problems, for which we would not have another solution. Factories can be another way to solve such problems.
So there is no real answer for your question, because DI is just one way besides others. It is just a pretty hip, although very elegant way.
I really enjoyed DI when I had this DAOs, which needed an SQLMapper. I just had to inject the different mappers into the fatherclass once and the rest was done by configuration. Saved me a lot of time and LOCs, but I still can't name this a problem for which there is no other solution.
I use dependency injection for testing all the time. It's also extremely helpful when you have a bunch of large systems that you do not want to directly tie together (extremely loose coupling).
If you're using Java, I would recommend Google Guice, since it rocks so much. For C++, I recommend Qt IOC. For .NET, the Castle Project provides a nice IOC system. There is also a Spring implementation basically everywhere, but that's boring.
DI allows you to create applications that can be configured and reconfigured without touching the codebase itself. Not just urls or settings though; generic objects can be written in code, and then "customized" or configured via XML files to achieve the specific result desired for the given case.
For example, I can create a RegexDetective class where the actual regex it looks for is provided in a setter, and then in my Spring DI XML file, define one actual regex expression for RegexDetective.setRegex() for a deployment of SleuthApp going to London. Then a few days later I can go back and update the regex in the XML file for another deployment of SleuthApp shipping out to Siberia.
DI also allows one to define specific implementations of interfaces in a similar fashion, outside of the codebase in XML, to modify behavior of an application without actually touching the code, such as setting the AngryDetective or ArcticDetective implementation of the Detective interface, in the DI XML file.
We run a multimedia service for different countries. We run the same code for everyone but sometimes, business rules are different from one country to another. In this case, we inject different Spring MVC Interceptor for one client or for another.
Then, in the deploy phase, a script "chooses" which DI file is needed, based on the last letters of the files (fr for France, ch for Switzerland etc...)
application-context.xml-fr
application-context.xml-ch
etc...
That's the only good use I see in DI. I'm not a fan of DI though.
I've used Spring's IoC (DI) container for the last three web apps I've developed. I don't think its suited to one particular type of problem, rather it's a different way of solving a problem. It's as you've said, a more flexible approach to large systems. My personal favourite features of DI are that you can prepare better unit tests because your classes are highly decoupled. Also important for me is code reuse. Since I use the container in many apps, I can use the same components and know that their dependencies will be fed in externally.
In large multi-module applications using DI, a module only depends on the interfaces on the collaborator of its classes, which cuts compile-time dependency graphs.
In the context of frameworks (calling "your" functional code, as opposed to functional code calling a library), this is required. Your code can have compiling dependencies to the framework, but we all know that the framework (out of your hands) could not have compile dependencies to your code ;-)
I use DI primarily for ease of testing. Additionally it fosters the model of stubbing out your service calls to provide isolation and the ability to implement independent of service development.
I have a web part that uses PortalSiteMapProvider to query the Sharepoint navigation hierarchy, but unit tests written for that code fail, because the code is being run outside the Sharepoint context and thus no site map providers are available.
I've identified two alternate ways of solving this dilemma:
Because Sharepoint is basically an elaborate ASP.Net application, it should be possible to run tests inside the Sharepoint context with the HostType and UrlToTest test attributes
Use a mock instead of PortalSiteMapProvider
Are either of these viable or is there a better third option?
The Microsoft Patterns and Practices dudes recommend TypeMock to help unit test Sharepoint
http://msdn.microsoft.com/en-us/library/dd203468.aspx
http://www.typemock.com/sharepointpage.php
Not a free solution unfortunately.
You will not be able to mock the SPRequest class, which is an internal class. I am facing the same issues.
One approach is to try to isolate your code from the SharePoint API, and this is not so nice.
BTW Typemock have a reduced price product especially for SharePoint.
Second option is more appropriate. Abstract away PSMP and hide it behind IPortalSiteMapProvider and then mock it in your unit test. In order to bridge the interface and concrete implementation you can either write a thin delegating adapter or use duck typing.
i wind up having about 20 different parameters in the constructor of the model class, one for each service? Is this normal or a sign that something is off.
I think, categorically, that your controller is interacting with too many services. I've not seen your code - so I'm going off assumptions - but it seems to me that your controller is composing business logic by calling numerous "small" services, rather than drawing on fewer, "larger" services that compose business logic from the smaller services.
Have a look around for information about "orchestration services" vs "entity" or "capability" services and you'll see what I mean. If you create orchestration services that provide your controllers with the logic they require, your architecture is improved because your controllers really should not contain any business logic at all.
I really think that the number of services you consume is the issue here. IoC containers may go some way to resolve how you bind types to your injection parameters etc., but I think the problem is your architecture at this point.
You might try consolidating some services or think about refactoring the controller-view parts in to smaller scoped components. Also, a dependency injection style framework like Spring can help with things like this.
Allthough I don't know your setup. 20 seems a bit much I think you go against the SRP (Single responsibility priniciple). But since I can't see your code it is impossible to tell. If you really need all these services in that one model class then perhaps you need to put them in a factoryclass and use that as a parameter.
It is hard to give any good answer on this since we don't know your domain.
As #Matt said a dependency injection could help you here and sprint.NET is a good one and there are several others.
Seeing as you mention MVP in particular, you should at least look at Ent Lib 4.1 which now has Unity, Microsoft's take on DI. Their codeplex site is probably a good place to start if this is new.
There are also software factories that integrate with visual studio and give you tools for creating MVP for web sites as linked or web services. These come from pattern and practices too.