I believe you must be familiar with this idiom, which is sort of java's excuse for closures
//In the "Resource Manager" class
public void process(Command cmd){
//Initialize
ExpensiveResource resource = new ExpensiveResource();
//Use
cmd.execute(resource);
//Release / Close
resource.close();
}
//In the Client class...
manager.process(new Command(){
public void execute(ExpensiveResource res){
//Do things with the resource
}
});
I used this idiom/pattern a lot but recently I tried to test it, and It's giving me a headache...
How do you get to test in isolation the ResourceManager and the Client classes? I found that this tight-couples them so much that you cannot do it easily.
Ideas are appreciated.
Regards
If you don't want to make the anonymous type a real type you can test, consider moving the code in its execute() function into another function that you can test. The anonymous type then becomes a humble object (http://xunitpatterns.com/Humble%20Object.html).
edit but you should continue finding a way to test the code in the anonymous function.
In a typesafe language like C#, this can be done by having the anonymous code call a virtual member function. The test specializes the class by overriding the virtual function call, checking it is called.
In a nontypesafe language like Javascript, the member function called is already virtual. So rather than create a derived type, you can overwrite the called member function with a recorded version.