MockBox – Mocking a Super Class – Solution

Yesterday I wrote about mocking a super class method while unit testing with MXUnit. If CFC A extends CFC B, and both have the same method name, how do I mock the super method for its call?

Luis Majano with ColdBox wrote up a Blog Post to address how to accomplish this.

Use my example from my previous post:

<!--- Child Class --->
<cfcomponent name="C" extends="message" output="false">
    <cffunction name="send" access="public" returntype="void" output="false">
        <cfargument name="name" type="string" required="true">
        <cfif name neq "test">
            <cfset super.send(name=arguments.name)>
        </cfif>
    </cffunction>
</cfcomponent>

<!--- Parent Class --->
<cfcomponent name="P" output="false">
    <cffunction name="send" access="public" returntype="void" output="false">
        <cfargument name="name" type="string" required="true">
        <!--- Do something --->
    </cffunction>
</cfcomponent>

The super scope is a reference in the variables scope. You can create a MockBox stub to accomplish mocking the super scope. This example creates an empty stub object that mocks the parent send method. The child’s super variable is then overwritten with this stub object. Stub objects are generally used to start working on a project where you are relying on other teams to build that object but has yet to be built.

function setup(){
    variables.mockBox = new mockbox.MockBox();
    variables.component = variables.mockBox.prepareMock( createObject("component","C") );
}

function testSend() {
    // create a virtual super scope and mock a send method on it
    mockSuper = variables.mockBox.createStub().$("send");

    // inject the mock super into the variables scope
    variables.component.$property("super","variables", mockSuper);

    // run the method call
    variables.component.super.$('send');</pre>
}

Luis also states that you can also create a mock of the parent class to leave the methods intact.

variables.mockBox.createMock("P").$("send");

I am still looking for opinions on if I should actually be doing this? Perhaps I should just consider the parent class as a whole and just let the parent method run. What are your ideas on this? How have you handled this in the past and how was your outcome?

Advertisements

#mockbox, #super-class