Should I create mocked using interfaces or concrete classes when interfaces are available?

124 views
Skip to first unread message

Ryan Taylor

unread,
Apr 1, 2012, 9:15:49 PM4/1/12
to mock...@googlegroups.com
Hello everyone.

When I am mocking objects to be passed into another method and those objects have interfaces on concrete classes should I create a mock of the concrete class or the interface, and why?  Here is an example to better example the question.  Should I write:

     var mockedLayerDetailsTask:ILayerDetailsTask = mockolate.nice(ILayerDetailsTask);
     var useIt:MyObject = new MyObject(mockedLayerDetails);

or should this be:

     var mockedLayerDetailsTask:ILayerDetailsTask = mockolate.nice(LayerDetailsTask);
     var useIt:MyObject = new MyObject(mockedLayerDetails);

It strikes me as unnecessary to mock the concrete class as I only care about the public methods and properties. In which case the first example would be preferred.  Could either choice have an impact on the time it takes to prepare mocks? Are there any other side effects?

Thanks,
Ryan

Hob Spillane

unread,
Apr 1, 2012, 9:23:32 PM4/1/12
to mock...@googlegroups.com

I only ever mock interfaces.  For one it enforces a string contract between your functional code and the object you're mock.  The other big reason is performance.  If the class you're mocking is a subclass of DisplayObject or UIComponent, it takes mockolate significantly longer to initialize your mock.  I can't speak to why this is exactly.  I've always guessed its a slowness in AS3's ability to reflect.  The interface can save you a few seconds on the creation of each mock.

-Hob

Drew Bourne

unread,
Apr 2, 2012, 12:14:38 AM4/2/12
to mock...@googlegroups.com
+1 for preferring interfaces, for the very same reasons Hob mentioned. 

There is very definitely a performance hit in mocking subclasses of UIComponent or other heavy class. It is not due to the reflection speed, it is due to the bytecode generation as Mockolate must override every accessor and method on the class and its superclasses when generating the proxy class. Using interfaces is much preferred as they usually have a shallow type hierarchy and relatively few accessors and methods. 

cheers, 
Drew

William Madden

unread,
Apr 15, 2012, 7:03:17 PM4/15/12
to mock...@googlegroups.com
That's probably worth publicising somehow.
Reply all
Reply to author
Forward
0 new messages