I have a Logging class which gets instantiated on startup of a console app and the stored in a static variable.
If i want a class to use the logger should it be passed to the class in the constructor or referenced directly?
I'm trying to write unit tests and either way i should be able to do it. Just means i have to set the static variable before calling the code that uses it.
Cheers.
Sounds like what you're looking for is some sort of IoC container. You could use EntLib's Unity or something else like that.
To make your classes as unit testable as possible, all dependencies, including loggers, should be passed in whenever possible. This is what is called Dependency Injection (DI), and is a very common and standard pattern for writing unit testable code. Logging is almost always a cross-cutting concern that is only embedded within the bodies of methods because there aren't really any decent AOP frameworks to properly pull those concerns out and apply them declaratively. Having to deal with logging when writing/running unit tests just increases the complexity of the tests, possibly adding additional configuration concerns, when you really want to keep your tests as simple and targeted as possible.
How about using the Static Gateway Pattern ?
You could create an instance of it and store that instance as a member of the same class & return that via a property.
e.g. Logger.Default
This will return the reference to the instance that was created.
EDIT: An example of this could be Console class & it's SetOut method.
I mean you can keep on using Console.WriteLine.... and if you want to change the stream, use the SetOut method. It redirects the output to a new stream.
Hope that helps.
Related
I'm relatively new to unit testing, and very new to C#, but I've been trying to test code that uses static classes with static methods, and it seems like I have to write huge amounts of boilerplate code in order to test, and that code would then also probably need to be tested.
For example: I'm using the System.Web.Security.Membership class, with a method ValidateUser on it. It seems like I need to create an interface IMembership containing the method ValidateUser, then create a class MembershipWrapper that implements IMembership, implementing the method ValidateUser and passing the arguments on to the actual Membership class. Then I need to have properties on my class that uses the Membership to reference the wrapper so that I can inject the dependency for a mock object during testing.
So to test 1 line of code that uses Membership, I've had to create an interface, and a class, and add a property and constructor code to my class. This seems wrong, so I must be getting something wrong. How should I be going about this testing? I've had a brief look at some frameworks/libraries that do dependency injection, but they still appear to require lots of boilerplate, or a very deep understanding of what's going on under the hood.
I don't see anything wrong in making your system loosely coupled. I believe you don't complain on creating constructor parameters and passing abstract dependencies to your classes. But instantiating dependencies in place looks so much easier, does it?
Also, as I pointed in comments, you can reuse wrappers later. So, that is not such useless work, as it seems from first glance.
You are on the right way, and think you are not testing single line of code, in this case you are writing important test to ensure that your code interacts with membership provider in the right way, this is not simple unit test rather "mock-based" integration test. I think it worth creating all these mocks and have covered by tests this part of application.
And yes, it seems overkill but no other way - either you use some helpers/libraries either wrap third-party static dependencies yourself.
I you're not happy taking the approach of constructor injection, you could look at using Ambient Context
You basically set up a default which will call System.Web.Security.Membership.ValidateUser
You then call the exposed method on the context in your code and you can now mock it for your tests
This allows you to write less setup code, but it also hides the fact that you have a dependency, which might be a problem in the future (depending on how you're reusing code)
If you're using VS2012, you can always use Shims in Microsoft Fakes for static calls (or .Net library calls too).
http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/hh549176.aspx
I have a static Configuration class responsible for data settings for my entire system. It loads certain values from the registry in its constructor, and all of its methods are based on these values. If it cannot get the values from the registry (which is possible if the application hasn't been activated yet), it throws an exception, which translates to a TypeInitializationException, which is fine by me.
I wrote unit tests using NUnit to make sure that Configuration's constructor handles all cases correctly - normal values, blank values, Null value. Each test initializes the registry using the relevant values and then calls some method inside Configuration.
And here's the problem: NUnit has decided to run the Null test first. It clears the registry, initializes Configuration, throws an exception - all is well. But then, because this is a static class whose constructor just failed - it doesn't re-construct the class again for the other tests, and they all fail.
I would have a problem even without the Null test, because Configuration probably (I'm guessing) gets initialized once for all classes that use it.
My question is: Should I use reflection to re-construct the class for each test, or should I re-design this class to check the registry in a property rather than the constructor?
My advice is to re-design your Configuration class a bit. Because your question is theoretical in nature, with a little practical aspect (failure of unit test), I'll provide some link to back-up my ideas.
First, make Configuration an non-static class. Miško Hevery, engineer at google, has a very good speech about OO Design for Testability where he specifically touches global state as a bad design choice, specially if you want to test it.
Your configuration could accept RegistryProvider instance through constructor (I assume you heard about Dependency Injection principles). RegistryProvider responsibility would be just read values from registry and that's the only thing, that it should do. Now when you test Configuration, you will provide RegistryProvider stub (if you don't know what stubs and mocks are - google it, they are simple in nature), where you will hardcode values for specific registry entries.
Now, benefits:
you have good unit tests, because you don't rely on registry
you don't have global state (testability)
your tests don't depend on
each other (each have separate Configuration instance)
your tests don't rely on environment, in which they are executed (you may not have permissions to access registry, but still you are able to test your Configuration class)
If you feel like you are not quite good at Dependency Injection, I would recommend a marvelous piece of art and engineering, provided to mortal souls by the genius of Mark Seemann, called Dependency Injection in .NET. One of the best book I've read about class design, which is oriented to .NET developers.
To make my answer more concrete :
Should I use reflection to re-construct the class for each test?
No, you should never use reflexion in your tests (only if it is no other case). Reflexion will make you tests:
fragile
hard to understand
hard to maintain
Use object-oriented practices with conjunction of encapsulation to achieve hiding of implementation. Then test only external behavior and don't rely on internal implementation details. This will make you tests depend only on external behavior and not on internal implementation, which can change a lot.
should I re-design this class to check the registry in a property
rather than the constructor?
Designing you class as described in my answer will make you able to test your class not accessing registry at all. This is a cornerstone of unit tests - not to rely on external systems (databases, file systems, web, registry, etc... ). If you want to test if you can access registry at all - write separate integration tests, where you will write to registry and read from it.
Now I don't have enough information to tell you whether you should read registry via RegistryProvider in Configuration constructor, or lazily read registry on demand, that's a tricky question. But I definitely can say - try to avoid global state as much as you can, try to minimize dependency on implementation details in you tests (this related to OO principles as a whole) and try to tests you objects in isolation, i.e. without accessing external systems. Then you can mimic exceptional cases, for example does you class behaves as expected when registry is no available? It is really hard to re-create such scenario if you access registry directly via static members of a Configuration class.
static classes / methods are notoriously hard to unit-test.
(Also notice that what you're currently doing isn't unit testing at all; it's integration testing (you're changing registry values for your tests).)
I'm afraid you'll have to choose between your class being testable and it being static.
A compromise you could make is to move the 'logical' bits (i.e validation etc.) to a different, non-static class, which will be called by the main static class.
That non-static class can be then easily tested.
I would opt for redesign.
Also having a TypeInitializationException if anything goes wrong could confuse the user/developer.
I would suggest adapting your code to use the singleton pattern as a first step.
I have been trying to use Ninject today and have a couple of questions. First of all do I need to use the Inject attribute on all constructors that I want to use injection for. This seems like a really lame design? Do I need to create a Kernel then use that everywhere I pass in an injected class?
The best way to get started with Ninject is to start small. Look for a new.
Somewhere in the middle of your application, you're creating a class inside another class. That means you're creating a dependency. Dependency Injection is about passing in those dependencies, usually through the constructor, instead of embedding them.
Say you have a class like this, used to automatically create a specific type of note in Word. (This is similar to a project I've done at work recently.)
class NoteCreator
{
public NoteHost Create()
{
var docCreator = new WordDocumentCreator();
docCreator.CreateNewDocument();
[etc.]
WordDocumentCreator is a class that handles the specifics of creating a new document in Microsoft Word (create an instance of Word, etc.). My class, NoteCreator, depends on WordDocumentCreator to perform its work.
The trouble is, if someday we decide to move to a superior word processor, I have to go find all the places where WordDocumentCreator is instantiated and change them to instantiate WordPerfectDocumentCreator instead.
Now imagine that I change my class to look like this:
class NoteCreator
{
WordDocumentCreator docCreator;
public NoteCreator(WordDocumentCreator docCreator) // constructor injection
{
this.docCreator = docCreator;
}
public NoteHost Create()
{
docCreator.CreateNewDocument();
[etc.]
My code hasn't changed that much; all I've done within the Create method is remove the line with the new. But now I'm injecting my dependency. Let's make one more small change:
class NoteCreator
{
IDocumentCreator docCreator;
public NoteCreator(IDocumentCreator docCreator) // change to interface
{
this.docCreator = docCreator;
}
public NoteHost Create()
{
docCreator.CreateNewDocument();
[etc.]
Instead of passing in a concrete WordDocumentCreator, I've extracted an IDocumentCreator interface with a CreateNewDocument method. Now I can pass in any class that implements that interface, and all NoteCreator has to do is call the method it knows about.
Now the tricky part. I should now have a compile error in my app, because somewhere I was creating NoteCreator with a parameterless constructor that no longer exists. Now I need to pull out that dependency as well. In other words, I go through the same process as above, but now I'm applying it to the class that creates a new NoteCreator. When you start extracting dependencies, you'll find that they tend to "bubble up" to the root of your application, which is the only place where you should have a reference to your DI container (e.g. Ninject).
The other thing I need to do is configure Ninject. The essential piece is a class that looks like this:
class MyAppModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentCreator>()
.To<WordDocumentCreator>();
This tells Ninject that when I attempt to create a class that, somewhere down the line, requires an IDocumentCreator, it should create a WordDocumentCreator and use that. The process Ninject goes through looks something like this:
Create the application's MainWindow. Its constructor requires a NoteCreator.
OK, so create a NoteCreator. But its constructor requires an IDocumentCreator.
My configuration says that for an IDocumentCreator, I should use WordDocumentCreator. So create a WordDocumentCreator.
Now I can pass the WordDocumentCreator to the NoteCreator.
And now I can pass that NoteCreator to the MainWindow.
The beauty of this system is threefold.
First, if you fail to configure something, you'll know right away, because your objects are created as soon as your application is run. Ninject will give you a helpful error message saying that your IDocumentCreator (for instance) can't be resolved.
Second, if management later mandates the user of a superior word processor, all you have to do is
Write a WordPerfectDocumentCreator that implements IDocumentCreator.
Change MyAppModule above, binding IDocumentCreator to WordPerfectDocumentCreator instead.
Third, if I want to test my NoteCreator, I don't have to pass in a real WordDocumentCreator (or whatever I'm using). I can pass in a fake one. That way I can write a test that assumes my IDocumentCreator works correctly, and only tests the moving parts in NoteCreator itself. My fake IDocumentCreator will do nothing but return the correct response, and my test will make sure that NoteCreator does the right thing.
For more information about how to structure your applications this way, have a look at Mark Seemann's recent book, Dependency Injection in .NET. Unfortunately, it doesn't cover Ninject, but it does cover a number of other DI frameworks, and it talks about how to structure your application in the way I've described above.
Also have a look at Working Effectively With Legacy Code, by Michael Feathers. He talks about the testing side of the above: how to break out interfaces and pass in fakes for the purpose of isolating behavior and getting it under test.
First of all do I need to use the Inject attribute on all constructors
that I want to use injection for. This seems like a really lame
design?
No you shouldn't have to do this at all actually. Since you work with ASP.NET MVC you can just install the Ninject.MVC3 Nuget package. This will get you started with a NinjectMVC3 class in the App_Start folder. You can use the RegisterServices method to register your interfaces/classes with Ninject. All controllers that have dependencies to those interfaces will then be automatically resolved by Ninject, there is no need for the Inject attribute.
Do I need to create a Kernel then use that everywhere I pass in an
injected class?
No - what you are describing sounds more like the Service Locator pattern, not dependency injection - you will want to pass in your dependencies ideally in the constructor, instead of resolving them within particular classes using the kernel. There should be just one central composition root where the resolving is done, which is within the composition root in either the RegisterServices method mentioned above or a separate Ninject module instantiated there - the later approach will allow you a little more flexibility and modularity (no pun intended) in changing how you resolve your dependencies.
Here's a good beginner's tutorial on dependency injection with Ninject and MVC3.
Don't forget there are docs, including an intro I feel would be very appropriate given the sort of questions you are asking on the Ninject Wiki. You're just annoying yourself if you're trying to use Ninject without reading it end to end.
Stick the table of contents on your bookmark bar for a bit.
I can also highly recommend Mark Seemann's Dependency Injection in .Net as a companion book for DI based architecture (even though it doesnt directly cover Ninject).
More specifically, What's the best approach for classes where state matters, within an application which implements Dependency Injection.
Say I need access to an object that's in a particular state. For example, this object might have been initiated in a different thread, or by a process I have no control over.
A good example of an object like this that already exists in .NET is the HttpContext.
In this case, Microsoft decided to go with the Static approach, so I just say:
var currentObj = HttpContext.Current;
And this gives me a particular instance of an object without having to worry where it came from.
The problem with the Static approach is that it doesn't play very nicely with dependency injection.
The other option is to configure your certain class as a Singleton in your IoC Container. This means that you can inject it, and depending on the current IoC Container config it'll be the correct instance of the class.
However, the downfall of this approach is that the stateful importance of the object is no longer explicit in the code, it's not obvious by looking at it. With the Static class used to access and instance it's more clear that the state is important. Maybe that doesn't matter though.
So, is there a pattern that helps me out here?
Context:
For context, I'm working on an application which has many instances of a class performing IO operations. They exists within their own threads.
I want to be able to interact with those objects (background tasks) via a web interface, so a Controller. I want to be able to interrogate them, and manipulate them etc.
Update:
Sorry, I think my use of the term "stateful" is a bit misleading. let me explain some thing:
"state" is probably the wrong word. I mean communicating with an object whereby I don't have control over it's lifecycle.
It is funny that I use "stateful" when talking about static classes. That's why I gave the HttpContext example, as that exactly what it does. The Current property gets you a very specific instance, not any new instance.
When I say that static doesn't play nice with DI, I meant, you can't inject Static classes. I could create a wrapper, yes, but I'm just pushing the problem elsewhere no?
I should have been more clear about my definition of Singleton. I meant a Singleton lifestyle, as defined in an IoC Container.
I always prefer Singleton over static. In fact, I almost never use statics in my own classes.
True singletons and static classes are both very difficult to write automated tests against. Do you mean a single instance looked up at runtime? That would make sense to me but I don't know the right construct to use in C#. The analog in Java is JNDI.
Neither or both. Presuming the stateful dependency is thread-safe the better approach is to build at least a basic layer of abstraction around said dependency then inject said abstraction into your classes. Singleton vs static becomes pretty immaterial then.
I'm building an application and as time goes on, I have more and more objects to initialize at startup. Moveover, some of the newer objects depend on others so I'm getting some kind of spaggetti initialization where objects are created then passed to other constructors. I'm suspecting that I'm getting it wrong.
For example I have a WinForm which accepts a "Controller" class and 2 events. The controller needs to be told about the existence of a DataGridView from the WinForm so it has a method
Controller::SetDataGridReference(DataGridView^ dgv)
Is there a general method of instanciating objects at startup then referencing those objects to each another?
I've been told that putting all the required classes as constructor parameters is a good practice but frankly, I don't see how I can do that here.
I don't really think that the language matters
This looks like a textbook case for using dependency injection (DI). It will certainly help with your spaghetti code and can even assist with unit testing. If you want to make a gradual migration towards DI you might want to consider refactoring the objects with similar relationships and using a few sets of factory classes that can handle all the boilerplate chain intialization as well as centralizing where all that takes place in your code base.
I can recommend Google Guice as a good DI framework for Java. Even if you arent using Java it is a good DI model to compare against other language's DI frameworks
Two patterns pop into mind as possibly appropriate depending on the specifics of your problem:
Abstract Factory Pattern. This can work with or without the Dependency Injection approach suggested by #Scanningcrew.
Mediator Pattern. Construct a mediator. Pass the mediator into the constructor of each object. Have each object register with the mediator. Then the objects don't need to know about each other explicitly. This works well when you have a set number of objects interacting with each other.
Use the Controller Design Pattern.
That is, create a SINGLE class that will be instanced on program initialization, called Controller. On the constructor of that class, create all other objects. Whatever object that needs any other objects should receive said object as a parameter on its constructor. No one, no absolutely any other object should create anything on their constructor. Pass everything as parameters on their constructors. Also, on the Controller class destructor/dispose call all objects destructor/dispose method in reverse order. This won't reduce your code, but it will make if far better to understand and debug later on.
Dependency Injection should help here: at application boot you can choice to build the complete (or sort of) graph of objects. The entry point of your application will instantiate the DI container of your choice, the you just request the root object.
For example Google Guice comes with a very nice Object grapher.
For the objects interaction, I would go for a Mediator. Check out this definition:
"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
For the instantiation, I would consider the Dependency Injection. Remember that you can freely use and mix design patterns to achieve your goals.