ColdMock Now Available at RIAForge

OK I've finished up my initial work on ColdMock and have released it as a project on RIAForge. The zip file and SVN repository contain the ColdMock factory as well as some examples of how it can be used.

I added what I think is a crucial element: validation of arguments and return values for the mocked methods. This was actually pretty challenging to add. This is because once the MockFactory creates an instance of your component, it purges all of the existing methods from that instance. It must do this so that your original methods don't run, since that defeats the whole point of using a Mock object. You don't want the original methods to run, since they will have code in them or references to other objects in them. Mocks just return the dummy data you specify. However, purging all the existing methods also means all the arguments, argument types, and return types are also gone.

To work around this, the Mock object uses the original component's metadata. When you call a method, onMissingMethod() runs. It then loops through the metadata and checks that all required incoming arguments are present, that the types are correct (if you specified a type in the original argument), and that the return value that you have specified is of the correct type as well (if you specified an original return type).

The possible combinations of untyped arguments, optional arguments, named vs. positional arguments, native types vs. CFC types, etc. made this quite difficult to implement. Basically, I had to write code that mimics all of CF's built in required argument and type checking! However, I believe I have it working for all of those situations. If anyone runs into a situation that isn't handled properly, please submit an issue at the RIAForge project.

del.ico.us del.icio.us | Digg It! Digg It! | Linking Blogs Linking Blogs | 2428 Views

Unit Testing with ColdMock To Dynamically Generate Mock Objects

I was at the RailsEdge conference in Chicago last week to hear some people talk about Ruby on Rails. I may post a separate entry about my thoughts on that conference and Rails, but this post goes in a different direction. One of the interesting things I saw was leveraging the dynamic nature of Ruby to create mock objects on the fly for use in your tests. It was a pretty cool idea since writing and managing "real" mock objects is kind of a pain. So I sat down and created a mock generator in ColdFusion in about an hour. I think I will call it ColdMock (not very original, I know, but I'm not a marketing guy).

If you are not familiar with Mock objects, here is the idea. When you test a CFC, you want to test ONLY that CFC. However, in a real application, CFCs often depend on other CFCs to work. It is very difficult to test these CFCs, because you're really testing the entire tree of dependent CFCs at once. To avoid this, you would substitute Mock objects for the dependent CFCs. As far as the CFC you are testing is concerned, the Mock objects act exactly the same as the real components. However, they have no actual code in them. They just return dummy data to the CFC you are testing. This way, you are only testing a single CFC, which is the entire point of a good unit test.

Up until now I have been writing (or, more often, using my CFC Stub Generator to generate) actual Mock CFC files. The problem is that you still have to go into the file and hard code return values for them. And if you need to call the method more than once during a test, you have to figure out some way to make the method return different values for the different calls. And the return values are then immutable, unless you go back in and re-edit the Mock CFC. It works, and it's definitely better than nothing, but ColdMock will make handling this much easier.

It works like this: you tell ColdMock which CFC you want to mock. It will create an instance of the original component, then purge all of its methods and dynamically attach a new set of methods that handle the mocking duties. This means that you no longer need to actually create a separate Mock CFC file. Once ColdMock gives you back your mock CFC, you declare what methods you want to mock and what values the mock method will return. Then you can test your CFC, and when it needs to call the CFCs it depends on, your Mock components will return whatever values you specified.

Since just reading the description of what it does might not make things clear, let's look at some code. I'll start with a very simple example. I want to mock out a SessionFacade component.

<!--- Create mock factory. --->
<cfset mockFactory = CreateObject('component','MockFactory').init() />
<!--- Create mock object. --->
<cfset facade = mockFactory.createMock('SessionFacade') />
<!--- Define mock return value. --->
<cfset facade.returns(32) />

<cfoutput>#facade.doSomething()#</cfoutput>
		

This creates the mock facade object, then says "when I call a method, any method, on the facade, return 32". You can also define multiple return values like this:

<cfset facade.returns(32,12,188) />
<cfoutput>#facade.doSomething()# #facade.doSomething()# #facade.doSomething()# </cfoutput>
		

Which will return a different value each time, based on the order you defined them. This works for fairly straightforward situations, but you might also need to define different values (or sets of values) for specific method calls. You can do this as well:

<cfset facade.mockMethod('getLastUserLogin').returns('1/1/2007') />
<cfset facade.mockMethod('getLoginCount').returns(42) />
<cfoutput>#facade.getLastUserLogin()# #facade.getLoginCount()#</cfoutput>
		

The return values can be anything. You can specify a string, a structure, or even a CFC instance, such as:

<cfset user = mockFactory.createMock('User') />
<cfset facade = mockFactory.createMock('SessionFacade') />
<cfset facade.returns(user) />
<cfdump var="#facade.doSomething()#" label="Dump the returned User object">
		

This should get across how the mocks work. The real benefit comes when you use them in your unit tests. You can create the mocks yourself, or if you use something like ColdSpring, you can have ColdSpring resolve the dependencies by creating mocks and injecting them into the CFC being tested.

Let's say I have a Trip CFC that I want to test. The Trip CFC depends on a SessionFacade CFC to do its work. I can create a ColdSpring XML file that my unit tests can all use which will handle the dependencies. It seems like a lot of work but it really isn't, and you probably can use one ColdSpring file to handle dependency resolution for all of your unit test files. Here is my simple ColdSpring XML:

<beans>   
   
	<bean id="trip" class="tests.coldmock.Trip">
		<property name="sessionFacade">
			<ref bean="MockSessionFacade"/>
		</property>
	</bean>
   
	<bean id="mockSessionFacade" factory-bean="MockFactory" factory-method="createMock">
		<constructor-arg name="objectToMock">
			<value>tests.coldmock.SessionFacade</value>
		</constructor-arg>
	</bean>
   
	<bean id="MockFactory" class="tests.coldmock.MockFactory" />
   
</beans>
		

Now, my CFCUnit test might look like this:

<cfcomponent name="TestTrip" extends="org.cfcunit.framework.TestCase">
   
	<cffunction name="setUp" access="public" output="false" hint="Runs before each test method.">
		<cfset var local = StructNew() />
		<cfset local.serviceDefinitionLocation = ExpandPath( '/tests/coldmock/coldspring.xml' ) />
		<cfset local.beanFactory = CreateObject('component', ' coldspring.beans.DefaultXmlBeanFactory').init() />
		<cfset local.beanFactory.loadBeansFromXmlFile(local.serviceDefinitionLocation) />
		<cfset variables.trip = local.beanFactory.getBean('trip') />
		<cfset variables.facade = local.beanFactory.getBean('mockSessionFacade') />
	</cffunction>
   
	<cffunction name="test_getDriverName" returntype="void" access="public" output="false" hint="">
		<cfset var local = StructNew() />
		<cfset variables.facade.returns('Brian') />
		<cfset assertEqualsString('Brian', variables.trip.getDriverName(), 'Driver name does not match.') />
	</cffunction>
   
</cfcomponent>
		

So now I can test my Trip CFC in total isolation. Even though it depends on the SessionFacade in my real application, I can substitute it with a mock to run my tests. I can easily define what the method calls to the mock objects will return right in my test. So I don't need to create or edit any Mock CFC files. This makes using mocks and writing good tests much easier.

Unfortunately, because it uses onMissingMethod(), it will only run on ColdFusion 8. This might not be a huge issue because most people will probably be running the developer edition of ColdFusion 8 locally. However, I'll keep trying to see if I can get it to work in a way that doesn't require onMissingMethod.

I'm still working on this but I should have something ready for release shortly. I'll be putting it up at RIAForge. In the meantime, I'm very interested to hear what people think. Any ideas, comments, or criticism of the idea?

Comments Comments (16) | del.ico.us del.icio.us | Digg It! Digg It! | Linking Blogs Linking Blogs | 5676 Views

Previous Entries