Any problems with putting DAOs and Gateways in Application.cfc? - coldfusion

Is it ok to put DAOs and Gateways that will be called many times but only need to be instantiated once in the Application scope?
Thanks

Yes, absolutely.
Another option is to use an IOC framework such as ColdSpring or some other bean factory. The bean factory can then be stored in the application scope and instantiated onApplicationStart() (effectively achieving the same thing but possibly with more control).

That's the perfect place to put them ;-).
Add them into onApplicationStart() as application.myDAO = xxxx & application.myGateway = xxxx and you're good to go!

Related

Simple definition of stub, spy, fake and mock in unit testing

I'm quite new to unit testing. I've read around on here as well as done some Googling, but am still a bit confused as to the meaning of each of the four meanings. I came across the following definition which help....
Stub - stubs are minimal implementations of interfaces or base classes
Spy - a spy will record which members were invoked
Fake - more complex, a fake may resemble a production implementation
Mock - A mock is usually dynamically created by a mock library and depending on its configuration, a mock can behave like a dummy, a stub, or a spy
However, I'd like to simplify the meaning (if possible) and ask a few questions.
Do all of the above only relate to functions, or can they be objects or any other type?
Stub - Is Stubbing bascially a way to provide dummy info instead of making the calling to the actual database? So for example, if I had an API call, instead of actually making a call to the API, I just instead make a GET request to a JSON file which is in my tests folder which has some dummy data in, and use that instead of making the API call?
Spy - so is this a way of tracking what happens to a function for example. Meaning you follow when it's called, where it gets passed around to?
Fake - Is this for example a function which you create inside the test file to mimic the real function or be a simpified version of the actual function?
Thanks in advance.
There are multiple attempts at definitions. To my knowledge there is no fully consistent definition, probably due to the fact that mocking frameworks defines things slightly differently. Martin Fowler lists the following (https://martinfowler.com/bliki/TestDouble.html):
Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example).
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.
Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent.
Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.
Fowler has them from this page: http://xunitpatterns.com/Test%20Double.html where you can read about them in a bit more detail.
No, they apply to more then just functions
Yes
Kind of, in most cases you will spy on an object
Yes
The implementation and nomenclatur will depend of what framework you use.

How to extend Unity container for automocking?

I want Unity to automatically inject mocks for dependencies of SUTs in unit tests.
I'd prefer some kind of IServiceProvider implementation to customize (if needed) mocks creation.
Is it possible?
P.S. We use TypeMock
Typemock implemented something similar to what you're looking for.
Fake.Dependencies creates a real SUT object, injecting faked parameters to its longest Ctor.
Passing some of the parameters manually is also possible, the rest are automatically faked.
UnderTest real = Isolate.Fake.Dependencies<SUT>([args])
You can also get a proxy to a fake dependency later in the test.
var fake = Isolate.GetFake<F>(real);
I'm sure that implementing your own solution is also possible.

Should dynamic dependencies of service objects be avoided?

This question is about testable software design based on mostly value objects and services.
Services that have static dependencies are straightforward to instantiate or configure when using a DI container. However, in some cases, services require dependencies that are known at runtime only.
Say, imagine a simple FileSystemDataStore with some CRUD methods in it for managing files in a directory. This service will need a directory name as one of its constructor parameters. That name could be known at runtime only and will have to be provided by its collaborators.
This seems to be somewhat of a problem because you can't configure such service in a DI container because of its dynamic nature. You'll probably have to use a factory to create such services. However, this will result in a quirk in the unit tests of the service's clients. You will have to mock the factory to return a mock of the service. This adds additional complexity to unit tests. Mocks returning mocks is often considered a test smell.
What is your opinion about this problem? Is it even a problem in your experience? Should such services be instead refactored to be more "pure"?
As a general observation, when services depend on run-time values, an Abstract Factory is indeed the appropriate response.
However, as pointed out in the question, this does have an impact on the maintainability of the tests, so if you can redesign the API to avoid such situations, you should do that. It's not always possible, though.
You would like to inject the directory name, but it is not known during the construction phase. I see three options here.
1. Inject a Provider
Instead of saying "Here is the directory name you need" you are saying "Here is an object that can give you the directory name at run-time". The way to implement this is to declaring a constructor argument Provider<String> directoryNameProvider. The constructor stores a reference to this provider as a member variable. When called apon to do some real-work in the run phase, the class would contain code like this when the directory name is needed:
directoryName = directoryNameProvider.get();
In java, the interface you implement is [javax.inject.Provider<T>][1]. This has a single method: get() which returns type T. The use of the generic provider interface means you do not have a proliferation of intefaces.
When it comes to your unit test, you can inject an anonymous inner class that implements the single method of Provider<T> to return a constant value easily enough. Our code base has a SimpleProvider<T> class that wraps a given object in the Provider interface.
Pro: Allows you to construct the object in the main construction phase. Unit testing is pretty easy.
Con: Details about dependency creation issues are leaking into the class when they should entirely be the concern of the factory. Too bad if the class is already written and accepts directoryName rather than directoryNameProvider already.
Despite the seemingly long list of cons, this is an option I use alot. It is my opinion that there is a missing language construct here.
2. Construct the troublesome object later
You can enter an inner scope when you know more. Within a run-phase method, you can enter a new scope. This means that you go through a whole new mini-construction phase, and then a mini-run phase. Ths is similiar to what happens in your application main() but at a smaller level.
Pro: Class receiving the dependency remains pure.
Con: Entering and exiting too many scopes can make the application and object life-cycles difficult to understand.
3. Use a method argument
You can decide that directoryName is to be a method argument and pass it to your class during the run phase rather than trying to inject it as a constructor argument. This is effectively deciding not to use dependency inject style for this occasion.
Pro: Simplicity
Con: Class that passes directoryName as a method parameter is tightly coupled to the class that needs it. It will be very difficult to implement an alternate implementation that depends on say, a database connection.
These are matters that I have been considering alot lately, so I'm interested in any comments or edits. Are there any other options?

What is the difference between using cfinvoke and createObject to run a component function?

In my company's code, I've often seen component files used by initializing an object of that component and calling the methods off the object. However, it seems to me somewhat more straightforward to use the cfinvoke method, especially when only using one method from the component file. What are the differences between these 2 methods of calling a component function and what are the pros/cons of each? When should I use which?
One other benefit of using createObject() is that you can chain the init() method, e.g.
<cfset myObject = createObject("com.path.MyObject").init() />
And if your init() returns this you can go further and chain the method if you don't need to use the object again:
<cfset functionResults = createObject("com.path.MyObject").init().myFunction() />
It's worth pointing out that in CF 9 you can use the new (ahem) new syntax to create objects. For example to create the same object as above and call it's init() I can write:
<cfset myObject = new com.path.MyObject() />
It's neat and I like the option to do this. CF is moving in the right direction in my opinion with features like this.
cfinvoke can only be used in tags.
createObject can be used in both tags & cfscript and tends to be a bit slimmer / easier to read IMO.
Until recently I avoided using cfinvoke because I found it "bulky" but a pro of it is you can dynamically loop over the methods within a CFC. In createobject you can't.
So if for example I've got a CFC which has the methods - method1, method2, method3, method4. I can loop over them like so:-
<cfloop from="1" to="4" index="element">
<cfif structKeyExists(this,'getMethod#element#')>
<cfinvoke component="#this#" method="getLine#local.element#" returnVariable="methodValue"></cfinvoke>
<cfset arrayAppend(myArray,methodValue) />
</cfif>
--
Another thing to note is that some sharing hosts lock down on createobject. Mainly because of the access it gives to the underlining Java.
You've nearly answered it yourself: on the surface, one could say that if you will be calling only one method on a page, then doing in one fell swoop in CFINVOKE (which instantiates the CFC and calls the one named method) make sense. And certainly if you would call more than one method of the CFC on a page, then separating the steps makes sense (instantiate the CFC with the createobject function or cfobject tag, then invoke methods as found in that object, a pointer to the CFC), so that you don't pay that instantiation cost more than once.
But do keep in mind that if the page is called often, it may make sense also to save that result of instantiating the CFC, so that it can be reused on a subsequent request to the page. You would do that by storing it (the result of cfobject/createobject) not in a local variable but instead in a shared scope: whether server, application, or session, based on "who" would benefit from such reuse. Of course, it's then incumbent on you to programmatically handle/decide how long to save this "cached" CFC instance.
As important, when you save a CFC instance this way, you become more susceptible to the "var scope bug", which basically is that you need to be still more careful to VAR any local variables you create in the CFC. Rather than try to elaborate more on that, I'll point out a meta-resource I created on that:
http://www.carehart.org/blog/client/index.cfm/2010/3/4/resources_on_the_var_scope_problem
Hope that helps.
Rather then rehash this discussion I'll just point you towards Google:
http://www.google.com/search?q=cfinvoke+vs+createobject
There are some subtle differences (IE: <cfinvoke> is capable of handling dynamic method names) but essentially it just boils down to personal preference. Well, that and the fact that you can't use <cfinvoke>via <cfscript>.

How to avoid duplicate code when using mocks in unittests

I am using dependency injection to supply mocks for code outside of my class under test. I find myself writing alot of the same code over and over as I need to mock out AuthProvider, ConfigurationManager, etc. which are used in the method I want to test. The method contains branches (if-then-else) and therefore I have multiple tests in place to test all execution paths of the method. I am instantiating each of the mocks several times (once in each test method) but am wondering if this is the wrong way around?
Also I am putting up expectations for the mocks and preset responses which evidently are mostly copy-paste as such calls as to AuthProvider.Authenticate() are called in every method
In each method I setup a mock repository and at the end of each method I verify the mock repository. Should I prehaps have some sort of factory for creating these mocks along with setting their expectations and return values and if so how?
For implementation of mocks I am using RhinoMocks.
"instantiating each of the mocks several times" is not a problem. Objects are free.
Just be sure you aren't defining the mock classes numerous times. Classes are expensive.
Also, you have a "setUp" method in a TestCase that allows you to create a fixture that is used by all tests. Yes, it's rebuilt for each test. No, that's not a problem unless it's painfully slow.
Assuming you're using NUnit, you can use instance variables for your Mocks and reset them in Setup/Teardown. If you see repeated patterns then do what you do with production code: refactor and extract helper methods that express what you're trying to achieve (if there's no commonality at all, then there's a problem with the design of the production code).
If there are significant divisions in setup, consider writing more than one test class for your production class.
Finally, think about whether your production class is just too busy and some of the behaviour ought to be extracted out to a helper object.
Listen to the Tests!
Here is my take..
I would not use mock in the case... I would use a factory method to return a fake implementation of the class and use dependency injection to use this implementation instead.. this way you would avoid duplication and can reuse this implementation again n again... again this factory implementation need to be refactored properly i.e., no duplication..
Mocks, I guess should be used when you are testing some dynamic behavior.. something like.. did a method in sub-system was called when I perform some action on SUT.. and later on call verify() to verify this behavior... there is also a good article on Martin Folwer bliki Mock Aren't Stubs
You might want to look at using the AAA style of test so that you have multiple tests with a common setup. Here's a decent example.
Record and Replay frameworks like EasyMock fail if you dont set an expectation on a mock call. But frameworks like Mockito simply record all calls and let you verify only the ones that matter. So you dont have to set expectation on all methods in all tests.
And coming back to your Problem of instantiating Mocks in each test method, there's a better way than using setUp() method. Mockito provides a #Mock annotation. So you declare your variables(as fields) like:
#Mock Repository repositoryMock
and just call initMocks() in setUp(). All mock objects declared are automatically available in your tests without explicitly creating Mocks.