Unit Tests Save Lives
Dec 07
My OO project, despite being for work, will only get attention from me in the evening hours for the time being. I've got a bit of a backlog at the office due to my time away with whatever type of flu that was (swine?). Nevertheless, I have it in front of me right now and am delighted to report that one of my unit tests failed!
In the previous post, I described a new process where I override the save function and call the isValidated() function in my validator. My test save() failed. Of course, this happened because my test required me to mock the Validator object which I hadn't done since modifying the process. But I take a certain amount of comfort in this failure. It lets me know that with proper testing, I can detect disasters before they make their way into production. It also lets me know that I need to keep my tests up to date when I make changes which is easy to note if you can exercise discipline and run your tests before packaging an upgrade.
For those interested in looking under the hood, here is my revised test that passes now.
<cffunction name="testDelegation" access="public" returntype="void">
<cfset var user = CreateObject("component","com.model.User").init() />
<cfset var mockBox = createObject("component","coldbox.system.testing.MockBox").init() />
<!--- Mock a Dao and force a true save() to ensure delegation of save method --->
<cfset userDao = mockbox.createMock(className="com.model.dao.UserDao") />
<cfset userDao.$(method="save",returns="true") />
<cfset user.setDao(userDao) />
<cfset userValidator = mockbox.createMock(className="com.model.validators.UserValidator") />
<cfset userValidator.$(method="isValidated",returns="true") />
<cfset user.setValidator(userValidator) />
<!--- This test will fail without setting a Dao/Validator --->
<cfset assertTrue(user.save()) />
</cffunction>