Search code examples
unit-testingcoldfusioncoldbox

How to mock a coldbox.system.web.context.RequestContext and initialize it?


I have inherited some code at my work. A previous person wrote some ColdFusion code that looks like this:

public struct function GetData(Event,RC,PRC){};

I am trying to write a unit-test for this function but I don't know how to mock this "Event". This is my code:

mockEvent=createMock(className='coldbox.system.web.context.RequestContext');

ColdBox is throwing an exception that I must initialize mockEvent when I run that code. Does anyone see what I am doing wrong?


Solution

  • Within a test, which extends the Coldbox.system.testing.BaseTestCase, you can easily mock the Coldbox RequestContext object.

    You need to set the following variable in your tests : this.loadColdbox=true and then, after you call the super.beforeAll() method from within your test, each time you call setup(), the context is rebuilt.

    After that, the RequestContext is available with the method getRequestContext(). Here's an example of mocking the request getHTTPMethod() function (I typically use this method to mock API methods which are configured to respond to different HTTP verbs):

    function newEventArgs( method = "GET" ) {
            //rebuild the context
            setup();
            //mock the context
            var event = getRequestContext();
            prepareMock( event ).$( "getHTTPMethod", arguments.method );
            var rc = event.getCollection();
            var prc = event.getCollection( private=true );
            prc.response = getWirebox().getInstance( "APIResponse" );
    
            return {
                "event":event,
                "rc":rc,
                "prc":prc
            };
    }
    

    Then you might test a create method like so:

    it( "Tests Widgets.create", function(){
    
            var testWidget = {
                "name"  : "Test Widget"
            };
    
            var eventArgs = newEventArgs( "POST" );
    
            structAppend( eventArgs.rc, testWidget, true );
    
            var event = execute( 
                route="/api/v1/widgets"
                eventArgs=eventArgs
            );
    
            expect( event.getPrivateValue( "response" ).getStatusCode() ).toBe( 201, "Event response did not return the proper status code." );
    
    });