Injecting a Mock into a Component Under Test - mxunit/mxunit GitHub Wiki

After you’ve created a mock and defined its behaviour, you’ll want to inject it into the component under test (CUT). That is a simple matter of passing it into the method that already exists to allow for dependency injection. This is generally done either via the constructor (init() method), or via a setter.

For example, if the CUT uses constructor injection:

<cfcomponent hint="Example Component To Mock" output="false">
    
   <cffunction name="init">
      <cfargument name="aCollaborator" />
      <cfset variables.myOtherComponent = arguments.aCollaborator />
      <cfreturn this />
   </cffunction>

</cfcomponent>

You would create and inject a mock like this:

<cfset myMock = mock() />
<cfset myMock.getName().returns('The Dude') />
<cfset myComponent = createObject('component','MyComponent').init(myMock) />

If the CUT uses setter injection:

<cfcomponent hint="Example Component To Mock" output="false">
    
   <cffunction name="setMyOtherComponent">
      <cfargument name="aCollaborator" />
      <cfset variables.myOtherComponent = arguments.aCollaborator />
   </cffunction>

</cfcomponent>

You would create and inject a mock like this:

<cfset myMock = mock() />
<cfset myMock.getName().returns('The Dude') />
<cfset myComponent = createObject('component','MyComponent') />
<cfset myComponent.setMyOtherComponent(myMock) />
⚠️ **GitHub.com Fallback** ⚠️