unit testing - How to test anonymous classes?

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.

网友答案:

I think that anonymous classes should be so small and simple that testing the structure including/using them should be good enough.

If you have something so complicated, big, important that you feel the need to test it make it a full class.

网友答案:

Don't use anonymous inner classes much (if at all). Aside from being difficult to test, they are virtually impossible to reuse without copy and paste.

Most of the time, making them full classes allows more flexibility and improves your OO design (adding more classes almost always improves your design).

By the way, as you mentioned closures also have the same problem--difficult to reuse.