I am developing an AS3 application which uses a Singleton class to store Metrics in Arrays. It's a Singleton because I only ever want one instance of this class to be created and it needs to be created from any part of the app.
The difficulty comes when I want to unit test this class. I thought adding public getters and setters would enable me to unit test this properly and would be useful for my app. I have read that changing to a Factory pattern will enable unit testing or using Inversion of control. This would of course make it more flexible too. I would like to know of people's thoughts on this matter as there are SO many conflicting opinions on this!
Thanks
Chris
If you're using an IoC framework, then make your consumers require an instance of the service in their constructor, and configure the IoC framework to only build one instance and keep handing it out to all requests in the entire application. This is the default behavior of Castle Windsor in my experience.
For unit testing you can use a Mock object in place of the real object.
Related
I have an application running on JBoss AS 7.1.1. This app uses some resources of CDI specification as interceptors, injection, etc. The architecture of my app is very simple with the structure below:
view (xhtml and facelets)
controller (managed beans with #Named, except in the ViewScoped)
model (divided in two layers, service and dao)
service (with #Stateless annotation, here I use an interceptor that I created to manage the transactions with database, because I use native JDBC)
dao
I need to create some scripts to test the application service layer, injecting the service implementation and invoking the business methods.
I believe that this architecture is very common. I'm sorry for my english.
Can someone help me, please?
Thanks!
If you want to test your full container, you probably want Arquillian. If you want to do Unit testing with mocks, start a standalone weld container in your test using weld-se.
new Weld().initialize().instance().select(YourClassName.class).get();
You can substitute your mock objects by using alternatives in your beans.xml. You can also use CDI-Unit which simplifies the process a bit.
I'd like to be able to register some types on a container and then top these up with some additional type declared in an XML configuration file. Unfortunately, IConfigurationInterpreter (implemented by XmlInterpreter) is only available in the WindsorContainer() constructor, not in any AddXXX() methods. Is there any other way I can achieve this without resorting to parent/child containers (that may soon be unsupported).
Background: Our large application is only starting to use the Castle framework to register and resolve some of it's components. Because Castle is being retrofitted into this app we're using a singleton class to maintain a global instance of WindsorContainer(). In unit tests, we need to wire up this container instance to use a combination of custom mock implementations (specific to the test) + some default mock implementations. For DLL dependency reasons, these mock class types are unavailable in this unit test fixture abstract base class so dynamic registration (using strings) is necessary. I was hoping to use an XML resource file to register the default mocks. Otherwise I have to do the same using an IWindsorInstaller implementation that's really duplicating what XmlInterpreter does. This API appears to be forcing this direction.
I think these will work ...
container.Install(Castle.Windsor.Installer.Configuration.FromXml(resource))
OR
container.Install(Castle.Windsor.Installer.Configuration.FromXmlFile(path))
which both avoid use of the IConfigurationInterpreter interface.
I'm about to embark on a new project using Windsor, but I've been wondering about running into scenarios where a Class A might need to instantiate Class B, but it's not feasible or possible for Windsor to inject an instance of Class B into it. I'm struggling to think of a scenario, but here goes:
Say I have a business entity "Customer" that gets passed to a WCF service. This class has an Ent.Lib self-validation method, which in turn uses a helper class "CustomerValidator". The Customer object received by the service has been deserialized by WCF, so Windsor plays no part in its instantiation, so I can't inject any dependencies. Nor can I pass my CustomerValidator to the self-validation method as it must follow a particular signature for Ent.Lib. So how could I instantiate the CustomerValidator within this class/method? I still want to utilise Windsor rather than simply doing a "var cv = new CustomerValidator();".
It's not a great example as it could be solved in different ways, e.g. passing the Customer object to a validation method rather than having the validation method in the Customer class, but it offers a possible scenario for discussion.
I could expose my WindsorContainer as a public singleton, accessible by any code that needs it, but that seems to be frowned upon. Any other suggestions?
should I reference the container from other classes?
No. By referencing the container, you add complicated and unnecessary dependency to your class which will complicate testing and increase complexity.
The Customer object received by the service has been deserialized by WCF, so Windsor plays no part in its instantiation, so I can't inject any dependencies.
I think this is the direction you should go, try to explore if there really isn't any way to take control of deserialization so you can inject dependencies.
If that fails, consider using http://commonservicelocator.codeplex.com/. Its Microsoft's service location implementation with Windsor adapter available. It's basically the same pattern as if you referenced the container but you don't introduce dependency on specific container implementation. Also I think it will be easier to mock for testing.
After reading the nice answers in this question, I watched the screencasts by Justin Etheredge. It all seems very nice, with a minimum of setup you get DI right from your code.
Now the question that creeps up to me is: why would you want to use a DI framework that doesn't use configuration files? Isn't that the whole point of using a DI infrastructure so that you can alter the behaviour (the "strategy", so to speak) after building/releasing/whatever the code?
Can anyone give me a good use case that validates using a non-configured DI like Ninject?
I don't think you want a DI-framework without configuration. I think you want a DI-framework with the configuration you need.
I'll take spring as an example. Back in the "old days" we used to put everything in XML files to make everything configurable.
When switching to fully annotated regime you basically define which component roles yor application contains. So a given
service may for instance have one implementation which is for "regular runtime" where there is another implementation that belongs
in the "Stubbed" version of the application. Furthermore, when wiring for integration tests you may be using a third implementation.
When looking at the problem this way you quickly realize that most applications only contain a very limited set of component roles
in the runtime - these are the things that actually cause different versions of a component to be used. And usually a given implementation of a component is always bound to this role; it is really the reason-of-existence of that implementation.
So if you let the "configuration" simply specify which component roles you require, you can get away without much more configuration at all.
Of course, there's always going to be exceptions, but then you just handle the exceptions instead.
I'm on a path with krosenvold, here, only with less text: Within most applications, you have a exactly one implementation per required "service". We simply don't write applications where each object needs 10 or more implementations of each service. So it would make sense to have a simple way say "this is the default implementation, 99% of all objects using this service will be happy with it".
In tests, you usually use a specific mockup, so no need for any config there either (since you do the wiring manually).
This is what convention-over-configuration is all about. Most of the time, the configuration is simply a dump repeating of something that the DI framework should know already :)
In my apps, I use the class object as the key to look up implementations and the "key" happens to be the default implementation. If my DI framework can't find an override in the config, it will just try to instantiate the key. With over 1000 "services", I need four overrides. That would be a lot of useless XML to write.
With dependency injection unit tests become very simple to set up, because you can inject mocks instead of real objects in your object under test. You don't need configuration for that, just create and injects the mocks in the unit test code.
I received this comment on my blog, from Nate Kohari:
Glad you're considering using Ninject!
Ninject takes the stance that the
configuration of your DI framework is
actually part of your application, and
shouldn't be publicly configurable. If
you want certain bindings to be
configurable, you can easily make your
Ninject modules read your app.config.
Having your bindings in code saves you
from the verbosity of XML, and gives
you type-safety, refactorability, and
intellisense.
you don't even need to use a DI framework to apply the dependency injection pattern. you can simply make use of static factory methods for creating your objects, if you don't need configurability apart from recompiling code.
so it all depends on how configurable you want your application to be. if you want it to be configurable/pluggable without code recompilation, you'll want something you can configure via text or xml files.
I'll second the use of DI for testing. I only really consider using DI at the moment for testing, as our application doesn't require any configuration-based flexibility - it's also far too large to consider at the moment.
DI tends to lead to cleaner, more separated design - and that gives advantages all round.
If you want to change the behavior after a release build, then you will need a DI framework that supports external configurations, yes.
But I can think of other scenarios in which this configuration isn't necessary: for example control the injection of the components in your business logic. Or use a DI framework to make unit testing easier.
You should read about PRISM in .NET (it's best practices to do composite applications in .NET). In these best practices each module "Expose" their implementation type inside a shared container. This way each module has clear responsabilities over "who provide the implementation for this interface". I think it will be clear enough when you will understand how PRISM work.
When you use inversion of control you are helping to make your class do as little as possible. Let's say you have some windows service that waits for files and then performs a series of processes on the file. One of the processes is to convert it to ZIP it then Email it.
public class ZipProcessor : IFileProcessor
{
IZipService ZipService;
IEmailService EmailService;
public void Process(string fileName)
{
ZipService.Zip(fileName, Path.ChangeFileExtension(fileName, ".zip"));
EmailService.SendEmailTo(................);
}
}
Why would this class need to actually do the zipping and the emailing when you could have dedicated classes to do this for you? Obviously you wouldn't, but that's only a lead up to my point :-)
In addition to not implementing the Zip and email why should the class know which class implements the service? If you pass interfaces to the constructor of this processor then it never needs to create an instance of a specific class, it is given everything it needs to do the job.
Using a D.I.C. you can configure which classes implement certain interfaces and then just get it to create an instance for you, it will inject the dependencies into the class.
var processor = Container.Resolve<ZipProcessor>();
So now not only have you cleanly separated the class's functionality from shared functionality, but you have also prevented the consumer/provider from having any explicit knowledge of each other. This makes reading code easier to understand because there are less factors to consider at the same time.
Finally, when unit testing you can pass in mocked dependencies. When you test your ZipProcessor your mocked services will merely assert that the class attempted to send an email rather than it really trying to send one.
//Mock the ZIP
var mockZipService = MockRepository.GenerateMock<IZipService>();
mockZipService.Expect(x => x.Zip("Hello.xml", "Hello.zip"));
//Mock the email send
var mockEmailService = MockRepository.GenerateMock<IEmailService>();
mockEmailService.Expect(x => x.SendEmailTo(.................);
//Test the processor
var testSubject = new ZipProcessor(mockZipService, mockEmailService);
testSubject.Process("Hello.xml");
//Assert it used the services in the correct way
mockZipService.VerifyAlLExpectations();
mockEmailService.VerifyAllExceptions();
So in short. You would want to do it to
01: Prevent consumers from knowing explicitly which provider implements the services it needs, which means there's less to understand at once when you read code.
02: Make unit testing easier.
Pete
In all my projects till now, I use to use singleton pattern to access Application configuration throughout the application. Lately I see lot of articles taking about not to use singleton pattern , because this pattern does not promote of testability also it hides the Component dependency.
My question is what is the best way to store Application configuration, which is easily accessible throughout the application without passing the configuration object all over the application ?.
Thanks in Advance
Madhu
I think an application configuration is an excellent use of the Singleton pattern. I tend to use it myself to prevent having to reread the configuration each time I want to access it and because I like to have the configuration be strongly typed (i.e, not have to convert non-string values each time). I usually build in some backdoor methods to my Singleton to support testability -- i.e., the ability to inject an XML configuration so I can set it in my test and the ability to destroy the Singleton so that it gets recreated when needed. Typically these are private methods that I access via reflection so that they are hidden from the public interface.
EDIT We live and learn. While I think application configuration is one of the few places to use a Singleton, I don't do this any more. Typically, now, I will create an interface and a standard class implementation using static, Lazy<T> backing fields for the configuration properties. This allows me to have the "initialize once" behavior for each property with a better design for testability.
Use dependency injection to inject the single configuration object into any classes that need it. This way you can use a mock configuration for testing or whatever you want... you're not explicitly going out and getting something that needs to be initialized with configuration files. With dependency injection, you are not passing the object around either.
For that specific situation I would create one configuration object and pass it around to those who need it.
Since it is the configuration it should be used only in certain parts of the app and not necessarily should be Omnipresent.
However if you haven't had problems using them, and don't want to test it that hard, you should keep going as you did until today.
Read the discussion about why are they considered harmful. I think most of the problems come when a lot of resources are being held by the singleton.
For the app configuration I think it would be safe to keep it like it is.
The singleton pattern seems to be the way to go. Here's a Setting class that I wrote that works well for me.
If any component relies on configuration that can be changed at runtime (for example theme support for widgets), you need to provide some callback or signaling mechanism to notify about the changed config. That's why it is not enough to pass only the needed parameters to the component at creation time (like color).
You also need to provide access to the config from inside of the component (pass complete config to component), or make a component factory that stores references to the config and all its created components so it can eventually apply the changes.
The former has the big downside that it clutters the constructors or blows up the interface, though it is maybe fastest for prototyping. If you take the "Law of Demeter" into account this is a big no because it violates encapsulation.
The latter has the advantage that components keep their specific interface where components only take what they need, and as a bonus gives you a central place for refactoring (the factory). In the long run code maintenance will likely benefit from the factory pattern.
Also, even if the factory was a singleton, it would likely be used in far fewer places than a configuration singleton would have been.
Here is an example done using Castale.Core >> DictionaryAdapter and StructureMap