mock/stub Component with MXUnit

646 Views Asked by At

I have a component called ComponentUnderTest.cfc looking as:

<cfcomponent output="false">
<cfset externalComponent = Component("Externalcomponent");

  <cffunction name="FunctionUnderTest" access="public"...>
     <cfset externalComponent.ExternalFunction()> 
  </cffunction>
</cfcomponent>

How can I mock/stub externalComponent.externFunction() in a MXUnit test componenent:

<cfcomponent displayname="ComponentTester" extends="mxunit.framework.TestCase>

 <cffunction name="MockForExternalFunction">
   .....
 </cffunction>
 ??????
 <cffunction name=TestComponent>
     <cfset componentUnderTest = CreateObject("ComponentUnderTest")>
     ?????
     <cfset componentUnderTest.FunctionUnderTest()>  <!--- should call MockForExternalFunction --->
 </cffunction>
</cfcomponent>
2

There are 2 best solutions below

2
On

You're going to have to inject the mocked component into componentUnderTest to replace the existing on.

You can do something like this:

// I took this lot from the docs Henry pointed you to: I'm not familiar with MXUnit's mocking framework, but this sounds right
mockedObjectWithMockedMethod = mock();
mockedObjectWithMockedMethod.ExternalFunction().returns(MockForExternalFunction());

function injectVariable(name, value){
    variables[name] = value;
}
componentUnderTest.injectVariable = injectVariable;
componentUnderTest.injectVariable("externalComponent", mockedObjectWithMockedMethod);

The thing with this that MockForExternalFunction() just provided the return value to return when ExternalFunction() is called, it's not called instead of ExternalFunction(). This should be fine, though.

0
On
<cfcomponent displayname="ComponentTester" extends="mxunit.framework.TestCase>

 <cffunction name="MockForExternalFunction">
   .....
 </cffunction>

 <cffunction name=TestComponent>
     <cfset componentUnderTest = CreateObject("ComponentUnderTest")>
     <cfset injectMethod(componentUnderTest, this, "MockForExternalFunction", "FunctionUnderTest") />
     <cfset componentUnderTest.FunctionUnderTest()>  <!--- should call MockForExternalFunction --->
 </cffunction>
</cfcomponent>

Inject Method

<cffunction name="injectMethod" output="false" access="public" returntype="void" hint="injects the method from giver into receiver. This is helpful for quick and dirty mocking">
    <cfargument name="Receiver" type="any" required="true" hint="the object receiving the method"/>
    <cfargument name="Giver" type="any" required="true" hint="the object giving the method"/>
    <cfargument name="FunctionName" type="string" required="true" hint="the function to be injected from the giver into the receiver"/>
    <cfargument name="FunctionNameInReceiver" type="string" required="false" default="#arguments.functionName#" hint="the function name that you will call. this is useful when you want to inject giver.someFunctionXXX but have it be called as someFunction in your receiver object">
</cffunction>