Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
mockBox = new testbox.system.MockBox();
// Within a TestBox Spec
getMockBox()/testbox/system/stubsany $getProperty(name [scope='variables']expect( model.$getProperty("dataNumber", "variables") ).toBe( 4 );
expect( model.$getProperty("name", "variables.instance") ).toBe( "Luis" );configBean.getKey('DebugMode');
configBean.getKey('OutgoingMail');//get a mock config bean
mockConfig = getMockBox().createEmptyMock("coldbox.system.beans.ConfigBean");
//mock the method for positional arguments
mockConfig.$("getKey").$args("debugmode").$results(true);
mockConfig.$("getKey").$args("OutgoingMail").$results('[email protected]');
//Then you can call and get the expected results//get a mock config bean
mockConfig = getMockBox().createEmptyMock("coldbox.system.beans.ConfigBean");
//mock the method for named arguments
mockConfig.$("getKey").$args(name="debugmode").$results(true);any $property(string propertyName, [string propertyScope='variables'], any mock)//decorate our user service with mocking capabilities, just to show a different approach
userService = getMockBox().prepareMock( createObject("component","model.UserService") );
//create a mock dao and mock the getUsers() method
mockDAO=getMockBox().createEmptyMock("model.UserDAO").$("getUsers",QueryNew(""));
//Inject it as a property of the user service, since no external injections are found. variables scope is the default.
userService.$property(propertyName="userDAO",mock=mockDAO);
//Test a user service method that uses the DAO
results = userService.getUsers();
assertTrue( isQuery(results) );//decorate the cache object with mocking capabilties
cache = getMockBox().createMock(object=createObject("component","MyCache"));
//mock the debug property
cache.$property(propertyName="debugMode",propertyScope="instance",mock=true);Spy like us!
void function doSomething(foo){
// some code here then...
local.foo = variables.collaborator.callMe(local.foo);
variables.collaborator.whatever(local.foo);
}function test_it(){
local.mocked = createMock( "com.foo. collaborator" )
.$spy( "callMe" )
.$spy( "whatever" );
variables.CUT.$property( "collaborator", "variables", local.mocked );
assertEquals( 1, local.mocked.$count( "callMe" ) );
assertEquals( 1, local.mocked.$count( "whatever" ) );
}myService = mockbox.createStub(extends="model.security.MyService");myFakeProvider = mockbox.createStub(implements="coldbox.system.cache.ICacheProvider");
myFakeProvider.getName();Come mock with me!
any $(string method, [any returns], boolean preserveReturnType='true', [boolean throwException='false'], [string throwType=''], [string throwDetail=''], [string throwMessage=''], [boolean callLogging='false'], [boolean preserveArguments='false'], [any callback])
$(...).$results(...)//Mock 3 values for the getSetting method
controller.$("getSetting").$results(true,"cacheEnabled","myapp.model");
//Call getSetting 1
<cfdump var="#controller.getSetting()#">
Results = true
//Call getSetting 2
<cfdump var="#controller.getSetting()#">
Results = "cacheEnabled"
//Call getSetting 3
<cfdump var="#controller.getSetting()#">
Results = "myapp.model"
//Call getSetting 4
<cfdump var="#controller.getSetting()#">
Results = true
//Call getSetting 5
<cfdump var="#controller.getSetting()#">
Results = "cacheEnabled"mockUser = getMockBox().createMock("model.User");
mockUser.$("isAuthorized").$results(false,true);configBean.getKey('DebugMode'); // Exists
configBean.getKey('OutgoingMail'); // Exists
configBean.getKey('IncmingMail'); // Does not exist (see the typo?)// get a mock config bean
mockConfig = getMockBox().createEmptyMock( "coldbox.system.beans.ConfigBean" );
// mock the method with args
mockConfig.$( "getKey" ).$args( "debugmode" ).$results( true );
mockConfig.$( "getKey" ).$args( "OutgoingMail" ).$results( "[email protected]" );
// Here's the new $throw call
mockConfig.$( "getKey" ).$args( "IncmingMail" ).$throws( type = "MissingSetting" );
// Then you can call and get the expected results
expect( function(){
mockConfig.getKey( "IncmingMail" );
} ).toThrow( "MissingSetting" );Boolean $once([methodname])// let's say we have a service that verifies user credentials
// and if not valid, then tries to check if the user can be inflated from a cookie
// and then verified again
function verifyUser(){
if( isValidUser() ){
log.info("user is valid, doing valid operations");
}
// check if user cookie exists
if( isUserCookieValid() ){
// inflate credentials
inflateUserFromCookie();
// Validate them again
if( NOT isValidUser() ){
log.error("user from cookie invalid, aborting");
}
}
}
// Now the test
it( "can verify a user", function(){
security = getMockBox().createMock("model.security").$("isValidUser",false);
security.storeUserCookie("valid");
security.verifyUser();
expect( security.$once("isValidUser") ).toBeTrue();
});Boolean $never([methodname])security = getMockBox().createMock("model.security");
//No calls yet
expect( security.$never() ).toBeTrue();
security.$("isValidUser",false);
security.isValidUser();
// Asserts
expect( security.$never("isValidUser") ).toBeFalse();function testGetUsers(){
// Mock a query
mockQuery = mockBox.querySim("id,fname,lname
1 | luis | majano
2 | joe | louis
3 | bob | lainez");
// tell the dao to return this query
mockDAO.$("getUsers", mockQuery);
}<cfdump var="#targetObject.$debug()#">function beforeAll(){
mockUser = createMock("model.security.User");
//Mock several methods all in one shot!
mockUser.$("isFound",false).$("isDirty",false).$("isSaved",true);
}//make exists return true in a mocked session object
mockSession.$(method="exists",returns=true);
expect(mockSession.exists('whatevermanKey')).toBeTrue();
//make exists return true and then false and then repeat the sequence
mockSession.$(method="exists").$results(true,false);
expect( mockSession.exists('yeaaaaa') ).toBeTrue();
expect( mockSession.exists('nada') ).toBeFalse();
//make the getVar return a mock User object
mockUser = createMock(className="model.User");
mockSession.$(method="getVar",results=mockUser);
expect( mockSession.getVar('sure') ).toBe( mockUser );
//Make the call to user.checkPermission() throw an invalid exception
mockUser.$(method="checkPermission",
throwException=true,
throwType="InvalidPermissionException",
throwMessage="Invalid permission detected",
throwDetail="The permission you sent was invalid, please try again.");
try{
mockUser.checkPermission('invalid');
}
catch(Any e){
if( e.type neq "InvalidPermissionException"){
fail('The type was invalid #e.type#');
}
}
//mock a method with call logging
mockSession.$(method="setVar",callLogging=true);
mockSession.setVar("Hello","Luis");
mockSession.setVar("Name","luis majano");
//dump the call logs
<cfdump var="#mockSession.$callLog()#">

numeric $count([string methodName])mockUser = getMockBox().createMock("model.User");
mockUser.$("isAuthorized").$results(false,true);
debug(mockUser.$count("isAuthorized"));
//DUMPS 0
mockUser.isAuthorized();
debug(mockUser.$count("isAuthorized"));
//DUMPS 1
mockUser.isAuthorized();
debug(mockUser.$count("isAuthorized"));
//DUMPS 2
// dumps 2 also
debug( mockUser.$count() );void $reset()security = getMockBox().createMock("model.security").$("isValidUser", true);
security.isValidUser( mockUser );
// now clear out all call logs and test again
security.$reset();
mockUser.$property("authorized","variables",true);
security.isValidUser( mockUser );Boolean $atLeast(minNumberOfInvocations,[methodname])// let's say we have a service that verifies user credentials
// and if not valid, then tries to check if the user can be inflated from a cookie
// and then verified again
function verifyUser(){
if( isValidUser() ){
log.info("user is valid, doing valid operations");
}
// check if user cookie exists
if( isUserCookieValid() ){
// inflate credentials
inflateUserFromCookie();
// Validate them again
if( NOT isValidUser() ){
log.error("user from cookie invalid, aborting");
}
}
}
// Now the test
it( "can verify a user", function(){
security = createMock("model.security").$("isValidUser",false);
security.storeUserCookie("invalid");
security.verifyUser();
// Asserts that isValidUser() has been called at least 5 times
expect( security.$atLeast(5,"isValidUser") ).toBeFalse();
// Asserts that isValidUser() has been called at least 2 times
expect( security.$atLeast(2,"isValidUser") ).toBeFalse();
});struct $callLog()security = getMockBox().createMock("model.security");
//Call methods on it that perform something, but mock the saveUserState method, it returns void
security.$("saveUserState");
//get the call log for this method
userStateLog = security.$callLog().saveUserState;
expect( arrayLen(userStateLog) eq 0 ).toBeTrue();Boolean $times(numeric count, [methodname])security = getMockBox().createMock("model.security");
//No calls yet
expect( security.$times(0) ).toBeTrue();
security.$("isValidUser",false);
security.isValidUser();
// Asserts
expect( security.$times(1) ).toBeTrue();
expect( security.$times(1,"isValidUser") ).toBeTrue();
security.$("authenticate",true);
security.authenticate("username","password");
expect( security.$times(2) ).toBeTrue();
expect( security.$times(1,"authenticate") ).toBeTrue();public any createMock([string CLASSNAME], [any OBJECT], [boolean CLEARMETHODS='false'], [boolean CALLLOGGING='true'])collaborator = mockbox.createMock("model.myClass");public any createEmptyMock(string CLASSNAME, [any OBJECT], [boolean CALLLOGGING='true'])user = mockbox.createEmptyMock("model.User");public any prepareMock([any OBJECT], [boolean CALLLOGGING='true'])myService = createObject("component","model.services.MyCoolService").init();
// prepare it for mocking
mockBox.prepareMock( myService );component extends=”testbox.system.BaseSpec” {
function beforeAll(){
//Create the User Service to test, do not remove methods, just prepare for mocking.
userService = createMock("model.UserService");
// Mock the session facade, I am using the coldbox one, it can be any facade though
mockSession= createEmptyMock(className='coldbox.system.plugins.SessionStorage');
// Mock Transfer
mockTransfer = createEmptyMock(className='transfer.com.Transfer');
// Mock DAO
mockDAO = createEmptyMock(className='model.UserDAO');
//Init the User Service with mock dependencies
userService.init(mockTransfer,mockSession,mockDAO);
}
function run(){
describe( "User Service", function(){
it( "can get data", function(){
// mock a query using mockbox's querysimulator
mockQuery = querySim("id, name
1|Luis Majano
2|Alexia Majano");
// mock the DAO call with this mocked query as its return
mockDAO.$("getData", mockQuery);
data = userService.getData();
expect( data ).toBe( mockQuery );
});
});
}
}<cfcomponent name="UserService" output="False">
<cffunction name="init" returntype="UserService" output="False">
<cfargument name="transfer">
<cfargument name="sessionStorage">
<cfargument name="userDAO">
<cfscript>
instance.transfer = arguments.transfer;
instance.sessionStorage = arguments.sessionStorage;
instance.userDAO = arguments.userDAO;
return this;
</cfscript>
</cffunction>
<cffunction name="getData" returntype="query" output="false">
<cfreturn instance.userDao.getData()>
</cffunction>
</cfcomponent>
//hard to mock in a method call
function checkEmail(email){
var validator = createObject("component","model.util.Validator");
return validator.isEmail(arguments.email);
}<cfproperty name="Validator" type="model" instance="scope" />
//or setter injection
<cffunction name="setValidator" access="public" returntype="void" output="false">
<cfargument name="validator" type="any">
<cfset instance.validator = arguments.validator>
</cffunction>targetObject = createObject("component","model.TargetObject");
//prepare it for mocking, don't remove any methods
prepareMock(targetObject);
//Create our mock collaborator
mockValidator = getMockBox().createEmptyMock('model.Validator');
//Mock the isEmail valid method
mockValidator.$("isEmail",true);
//Inject it with setter injection
targetObject.setValidator(mockValidator);
//Inject it via mock property
targetObject.$property("validator","instance",mockValidator);function checkEmail(email){
return instance.validator.isEmail(arguments.email);
}
//or
function checkEmail(email){
return getValidator().isEmail(arguments.email);
}function userValidator(rule){
//validate a user
var user = getUserSession();
if( user.isAuthorized() ){
return true;
}
//Check if single sign on cookie exists and is valid
if( isSSOCookieValid() ){
authorizeUser(user);
}
else{
return false;
}
}function beforeAll(){
//target object
security = prepareMock( createObject("component","model.Security") );
//create a mock user object
mockUser = createEmptyMock("model.User");
}
function run(){
describe( "A user", function(){
it( "can be authenticated", function(){
//mock user authorizations according to case calls
mockUser.$("isAuthorized").$results(true,false,false);
security.$("getUserSession", mockUser);
//case 1: authorized user
expect(security.userValidator()).toBeTrue();
//case 2: unauthorized user with invalid cookie
security.$("isSSOCookieValid",false);
expect( security.userValidator() ).toBeFalse();
//case 3: unauthorized user with valid cookie
security.$("isSSOCookieValid",true);
//mock the authorizeUser void call
security.$("authorizeUser");
expect( security.userValidator() ).toBeTrue();
});
});
}Boolean $atLeast(minNumberOfInvocations,[methodname])// let's say we have a service that verifies user credentials
// and if not valid, then tries to check if the user can be inflated from a cookie
// and then verified again
function verifyUser(){
if( isValidUser() ){
log.info("user is valid, doing valid operations");
}
// check if user cookie exists
if( isUserCookieValid() ){
// inflate credentials
inflateUserFromCookie();
// Validate them again
if( NOT isValidUser() ){
log.error("user from cookie invalid, aborting");
}
}
}
// Now the test
it( "can verify a user", function(){
security = createMock("model.security").$("isValidUser",false);
security.storeUserCookie("valid");
security.verifyUser();
// Asserts that isValidUser() has been called at most 1 times
expect( security.$atMost(1,"isValidUser") ).toBeFalse();
});