Blog

Gavin Pickin

March 18, 2016

Spread the word


Share your thoughts

Are you writing APIs? Going to start writing APIs? Now is the time to start testing. Do it early, and often, and reap the benefits as the project grows. TestBox, the defacto CFML test suite, can help your test your API, whether it’s CFML or not.

I will assume you have the basic TextBox installation setup.
 

#box install testbox
    

You have a folder structure like this
/tests/
/tests/runner.cfm
/tests/specs/

 

Runner.cfm could look something like this

<cfsetting showDebugOutput="false">
<!--- Executes all tests in the 'specs' folder with simple reporter by default --->
<cfparam name="url.reporter"         default="simple">
<cfparam name="url.directory"         default="tests.specs">
<cfparam name="url.recurse"         default="true" type="boolean">
<cfparam name="url.bundles"         default="">
<cfparam name="url.labels"             default="">
<!--- Include the TestBox HTML Runner --->
<cfinclude template="/testbox/system/runners/HTMLRunner.cfm" >

 

Let’s assume your API is written in CFML, lets look at how you write those tests.
Let’s add a new spec file for our CFML CFC tests, in this file.
/tests/specs/cfcTest.cfc

Note: The API we're testing in here is not a real world example. In a true REST Api you wouldn't have a function called login. You would pass an authentication token with each request, but for simple example, I am using login to show the inputs, and expected outcomes. 

We’re going to add a single describe blog, with three tests ( it blocks ).
In these tests, we’re going to initialize a CFC, and then expect the return of a CFC function call to be a specific result.

Our first test, we’re creating a userServiceRemote cfc.
When we call userServiceRemote.login() with the email “gavin@gavin.com” and the password “topsecret”, the struct returned will have a key ‘result’, and we expect that result to be 400, for a bad login.

In our third test, again we create the CFC, we call login, but this time we’re calling with “gavin@gavin.co.nz” and the password “topsecret”, this time, with correct credentials, the struct with key result returns a 200, for success.

component extends="testbox.system.BaseSpec" {       

    function run() {            
        describe("userService API Login", function(){            
            it( "will error with incorrect login", function(){    
                var oTest = new cfcs.userServiceRemote();
                expect( oTest.login( 'gavin@gavin.com', 'topsecret').result ).toBe('400');
            });            
            it( "will error with incorrect password", function(){
                var oTest = new cfcs.userServiceRemote();
                expect( oTest.login( 'gavin@gavin.co.nz', 'notsecret').result ).toBe('400');
            });
            it( "will success with correct login", function(){
                var oTest = new cfcs.userServiceRemote();
                expect( oTest.login( 'gavin@gavin.co.nz', 'topsecret').result ).toBe('200');            
            });
        });
    }

}

Ok great, simple TestBox tests, using CFML CFC creation, and calling functions, Unit test style.
These tests run fast, you can test all your code, inside and out.


What if we want to test the Request Headers, Verbs, or our API isn’t even written in CFML. TestBox can do that easily, using CFHTTP, instead of Unit Tests, you’re running Integration tests. Here is how we would write the same tests, hitting the API endpoints.

In this example, instead of creating an instance of a CFC, we build a URL, and we call it with CFHTTP. The example below uses a get, for simplicity, but the same can apply to other verbs.
We call the endpoint, passing the email address, and the password, and store the result in the “cfhttpResponse” variable. Once we deserialize the json for the cfhttpResponse.filecontent, we check the “result” key, and see if the return code is 400.

 

it( "will error with incorrect login", function(){
    var email = "gavin@gavin.com";
    var password = "topsecret";
    var cfhttpResponse = "";
    http url="http://www.testableapi.local.com:8504/user/login/email/#email#/password/#password#" result="cfhttpResponse";
    expect( DeserializeJSON(cfhttpResponse.filecontent).result ).toBe('400');
});

The full test spec might look like this.

 

component extends="testbox.system.BaseSpec" {
    function run() {
        describe("userService API Login", function(){
            it( "will error with incorrect login", function(){
                    var email = "gavin@gavin.com";
                    var password = "topsecret";
                    var cfhttpResponse = "";
                    http url="http://www.testableapi.local.com:8504/cfcs/userServiceRemote.cfc?method=login&email=#email#&password=#password#" result="cfhttpResponse";
                    expect( DeserializeJSON(cfhttpResponse.filecontent).result ).toBe('400');
            });
            it( "will error with incorrect password", function(){
                    var email = "gavin@gavin.co.nz";
                    var password = "notsecret";
                    var cfhttpResponse = "";
                    http url="http://www.testableapi.local.com:8504/cfcs/userServiceRemote.cfc?method=login&email=#email#&password=#password#" result="cfhttpResponse";
                    expect( DeserializeJSON(cfhttpResponse.filecontent).result ).toBe('400');
            });
            it( "will success with correct login", function(){
                    var email = "gavin@gavin.co.nz";
                    var password = "topsecret";
                    var cfhttpResponse = "";
                    http url="http://www.testableapi.local.com:8504/cfcs/userServiceRemote.cfc?method=login&email=#email#&password=#password#" result="cfhttpResponse";
                    expect( DeserializeJSON(cfhttpResponse.filecontent).result ).toBe('200');
            });
        });  
    }
}


These tests are much slower, since you’re firing off the http calls, but they test your full integration. Testing like this also gives you access to the full response object, so your tests have the ability to check headers, call with different verbs, and so much more than you would just doing Unit Tests.

Recent Entries

Into the Box 2024 Last Early Bird Days!

Into the Box 2024 Last Early Bird Days!

Time is ticking, with less than 60 days remaining until the excitement of Into the Box 2024 unfolds! Don't let this golden opportunity slip away; our exclusive Early Bird Pricing is here for a limited time only, available until March 31st. Why wait? Secure your seat now and take advantage of this steal!

Maria Jose Herrera
Maria Jose Herrera
March 20, 2024
Ortus February Newsletter 2024

Ortus February Newsletter 2024

Welcome to Ortus Solutions’ monthly roundup, where we're thrilled to showcase cutting-edge advancements, product updates, and exciting events! Join us as we delve into the latest innovations shaping the future of technology.

Maria Jose Herrera
Maria Jose Herrera
March 06, 2024
Unveiling the Future of CFML Development - 3rd Round of Sessions

Unveiling the Future of CFML Development - 3rd Round of Sessions

Welcome back to our journey into the future of CFML development! As excitement continues to build for Into the Box 2024, we're thrilled to bring you the latest updates on what promises to be a transformative event. Continuing our blog post series, let's delve deeper into the third wave of session releases and discover the key surprises awaiting attendees. Learn More

Maria Jose Herrera
Maria Jose Herrera
March 01, 2024