我有一个名为ComponentUnderTest.cfc的组件,如下所示:
<cfcomponent output="false">
<cfset externalComponent = Component("Externalcomponent");
<cffunction name="FunctionUnderTest" access="public"...>
<cfset externalComponent.ExternalFunction()>
</cffunction>
</cfcomponent>
如何在MXUnit测试组件中模拟/存储externalComponent.externFunction():
<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>
答案 0 :(得分:0)
您必须将模拟组件注入componentUnderTest
以替换现有组件。
您可以这样做:
// 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);
这个问题MockForExternalFunction()
只提供了在调用ExternalFunction()
时返回的返回值,它不是名为而是的ExternalFunction()。但这应该没问题。
答案 1 :(得分:0)
<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>
<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>