How to Create a Generic Class for Mocking REST Callouts for Unit Test

I’m starting a new habit of posting regularly on my blog every Monday. I’ll be kicking it off with tips for creating a generic class or a mocking factory for mocking calls to an external third-party service.

Why do we need to do a mock?

When running unit tests the platform does not allow to do a callout to external dependencies. To test our code base we would need to mock the response as if calling the third party dependency.

By mocking we focus on the code being tested, isolating it from the state and behavior of the external system. The dependencies are simulated and the output state can be controlled.

To start we create a class that implements the HttpCalloutMock. This class enables sending a fake response when doing HTTP callouts. When our code makes a callout, the response will come from our HttpCalloutMock class.

When creating the class we define the constructor and parameters. We can make it generic and serve as a mock factory. Instead of writing several mock classes for every type of response, we only write it once which promotes code reusability best practices. And during unit testing, we define the mock response on the fly.

Here is our sample class which implements the HttpCalloutMock.

And if we have a class that does an HTTP Callout and we want to write a unit test for it. This is how it going to look like.

This is how we would create a unit test.

Key Takeaways

  • Use named credentials when possible when doing HTTP Callouts. Will talk about this more in the future.
  • When writing the unit test, the key is to call Test.setMock() which makes sure any callout from your code will return the Mock object.
  • Define the mock response on the fly to test different response.

Hope you find this useful. Stay tuned for more coding contents and tips. If interested with the source code it is available in GitHub.

Takeaways From Creating My First IOS Mobile App

Sticking to the goals I’ve set this year I wanted to create a mobile app that even though small will add value to the users. I’ve been using similar existing apps that allow you to track the money you’ve saved so for a particular goal say for example a new motorbike, a vacation or a new house. Most of the apps have heaps of annoying ads and the pro version where bit overpriced IMHO. Scratching my own itch and being a software engineer that I am I studied how I can build my own app. Here are my notes and takeaways.

Key Learnings:

  • Download and install Xcode – grab it from the Appstore. Is the major tool for developing apps that run on the Mac platform.
  • Creating a
    • New Project
      • Choose a template for either iOS, watchOS, tvOS, macOS
    • Playground – allows to you write basic prototypes and quickly validate some of the standard classes and methods
  • Explore the User Interface – learn the basic shortcuts, customize fonts and preferences, use tabs, view documentation, create snippets
  • Start using Git as early as possible to get used to versioning your code
  • Based on the MVC design pattern – model is the database, the view is the UI and uses the controller to bridge the UI and model.
  • Learn the Interface Builder components – scenes, initial view, how to connect to view controllers, adding components to the scene
  • Learn pins and constraints – basically pinning an object to object or window on the layout
  • Learn how to compile and debug – work with schemas, use debugger, unit tests
  • Cocoa Touch classes – eg UITableViewController, UITableViewCell. Mostly extending the main UIViewController
    • Each class has its own stub methods implementation
    • Custom UITableViewCell
  • Using the First responder – is the current object receiving events, when using text fields you tell the object to resign itself so that it hides the keyboard.
    • You can also use events like touchesBegan when a user taps anywhere else and then call resign the first responder
    • Using delegates – events in the text fields can be handled by the main controller
    • on viewDidLoad
      • textField.delegate = self
  • Learn how to create UI elements using code – navigation menu, labels, buttons, etc.
    • using .frame, .center and CGFloat and CGRect for positioning elements
    • drawing and animating UI elements with CAShapeLayer and CABasicAnimation
  • Using Core Data – using manageObject and NSPersistentContainer to load data into the controller from your model
    • data modeling with attributes and relationships
    • creating, updating and deleting Core Data
  • Navigation controller – use for containers for view controllers that allows transitions from one another and manages the titles
    • learn segue, identifiers and how to pass data from one view to another
    • unwinding segue
  • Know the concepts of instantiating nil – basically, you need to check that a particular instance of an object is not empty and only then can you use it in your logic else your application will crash
  • AppDelegate – handle application-wide events
  • Using UICollectiionView components –
    • UICollectiionViewDelegate – selecting and highlighting collection view elements
    • UICollectionViewDataSource – provides data and views required for the collection view
    • UICollectionViewDelegateFlowLayout – can be used to allow horizontal scrolling
  • Using Notification Center – use UNUserNotificationCenter
    • creating notifications using DateComponents and Calendar
  • Human Interface Guidelines
    • App icons need to be pixel perfect for all device types
    • If you going to have a launch screen make sure that is consistent or the transition is not abrupt
  • You can develop apps locally and to start distributing or testing it on a device you need to sign up for the Developer Program.
    • I needed to be on the developer program(cost $ 100USD yearly) before I can test on a device. I couldn’t figure out how to do it without one.
    • If you need the company name listed on the app store instead of the individual then you need to be in the DUNS sytem during registration. If not you can still do register for DUNS after you signed up. DUNS registration is free and processing takes about a couple of weeks. After that, you can email apple to change your account from individual to a company account.
  • Certificates, Identifiers, and Profiles – used for preparing your app for distribution. Create one for development and another one for release to production for the App Store
    • Download the certificates and import it to your project and assign the teams
  • AppStore Connect – use to submit your app and what will appear in the App Store listing
    • on Xcode archive and upload the app
    • check all the required fields and create screenshots of your app for an enticing listing on the App Store
    • Watch out for typos. I was rushing putting the free version in and made a dumb mistake on the naming.

So that was in summary what I did and there is still a whole lot of area that I didn’t need for my MVP. Sure enough, will start incorporating some more functionality on the app on future upgrades like using iCloud and security then share how I did this here on the blog and on my youtube channel.

My 2018 recap and 2019 plans

My first post of the year and what better way to kick off but by having a fresh new theme layout. I have lots of stuffs plan for the my blog this year so stay tune.

Anyway my 2018 was probably the busiest I have been as I reached new goals in terms of career and knowledge. I managed to knocked down Salesforce and integration certification one after another like dominoes. I’m now eligible to take the Salesforce Certified Technical Architect exam board.

These are the certifications I achieved for 2018.

  • Salesforce Certified Sharing and Visibility Designer
  • Salesforce Certified Application Architect
  • Salesforce Certified Data Architecture & Management Designer
  • Salesforce Certified Identity and Access Management Designer
  • Salesforce Certified System Architect
  • Salesforce Certified Development Lifecycle & Deployment Designer
  • Salesforce Certified Integration Architecture Designer
  • Salesforce Certified Platform Developer II
  • Salesforce Certified Field Service Lightning Consultant
  • Certified Mule 4 Developer
  • Certified Boomi Developer

But there is one hurdle, my weakness, my kryptonite.. my presentation skills lacks evoking confidence. (feedback from one of the senior manager). I need to up my game on my communication skills and be more engaged.

For 2019 I’m approaching stuffs a little differently. First off I need to fix my damn finances as I really let go on 2018. I barely invested, didn’t build assets and got myself into some debt( not huge) but I do not normally get into debts.

My mentality and approach this year is to build assets as well as upping my communication skills.

  • I’ll be starting a free series of Youtube tutorials for Salesforce Architecture, Mulesoft and web development – this should increase my subscribers and get me back on the Youtube Partner Program
  • I’ll start a paid course in Salesforce and Mulesoft
  • Not too serious approach on my merch that I sell in Amazon
  • Scratch my itch and build some mobile app
  • Build a Saas – brain dump my knowledge on CICD, etc.
  • Colloborate more and try to get Salesforce MVP status (how this is an asset I don’t know yet)

So basically anything that I do should lead to building an asset. It could be passive income projects, part time work to buy assets like real estate, stocks and crypto.

How to open Internet downloaded apps on a Mac

macOS includes a technology called Gatekeeper, that’s designed to ensure that only trusted software runs on your Mac. The safest place to get apps for your Mac is the App Store. … If you download and install apps from the internet or directly from a developer, macOS continues to protect your Mac.

To disable the Gatekeeper you can do one of the following steps.

Open up the terminal( a command line utility) and enter the following
sudo spctl --master-disable
You will be prompted for your Administrator password.

Then you can now run the internet downloaded application.

To enable it back simply run the alternate command.
sudo spctl --master-enable

Passed the Mulesoft Certified Developer(Mule4) Level 1 Exam

This one was a very tough exam to prepare for. Even with having taken the online 5 day Fundamentals course last August. I failed my first attempt of the exam last week. So I booked another schedule the week after and really focused on the skills and concepts I was lacking.

The self study material is now available. Enroll and sign up here

The format of the exam is a multiple choice. There are a total of 60 questions and passing score is 70 and you are alloted 120 minutes.

Start by reviewing the Study Guide

Here are my notes for passing the exam.

  • Creating Application Networks
    • Current IT landscape problem
      • IT cannot delivery fast enough
      • IT can build fast while still early but as time moves the IT project gets complex and harder to build on top of it
      • Solution: A new IT operating model IT builds reusable assets and data Business can self-serve on the assets
    • Modern API  approach
      • discoverable and accessible through self service
      • productized and designed for ease of consumption
      • easily managed for security, scalability and performance
      • API-Led Connectivity
        • Experience API
        • Process API
        • System API
    • What is C4E ?
      • Center for Enablement
      • A cross functional team
        • developers
        • lob it
        • central it
      • C4E make sure assets
        • are productized
        • consumable
        • fully leveraged
      • success is based on asset consumption
    • Deconstructing API
      • What is an API?
        • Acronym for Application Programming Interface
        • it provides information how to communicate with a software component
          • Operations – what to call
          • Inputs – what inputs are expected Output – results expected
          • Underlying data types ?
        • It defines functionalities independent of implementations
          • change what is behind the scenes without people changing how they call it
      • API can be of the following
        • API specification file
          • defines what to call, send and get back
        • web service
          • actual API implementation you can make calls
        • API proxy
          • application that controls access  to a web service, restricting access and usage through an api proxy
      • What are web services
        • different software systems often need to exchange data with each other
          • bridges platform, protocols, programming language and hardware architecture
        • is a method of communication between systems over the internet
        • system interaction manner is prescribed by some defined rules of communication
      • Parts of a web service API
        • The web service api
          • describes how to interact with the api
          • may or may not be defined in a file
        • web service interface implementing an api
          • code providing structure to the application/ combination
        • web service implementation itself
          • actual code and application
      • Two main API types
        • SOAP
          • traditional, more complex
          • communication rules are defined in an XML
        • RESTful
          • recent, simplier
          • uses existing HTTP communication protocol
          • Representational State Transfer
            • architecture pattern where clients and servers exchange representation of resources using HTTP protocols
            • http request methods
              • POST
                • creates new resource
              • GET
                • retrieves current state normally in XML or JSON
              • PUT
                • updates or creates a new one
              • PATCH
                • partially updates
              • DELETE
                • deletes a resource
            • data and resources are represented using URIs
            • resources are accessed or managed with a fixed set of operation
              • get /companies
              • get /companies?country=France
              • etc…
            • Example RESTful web service response
              • JSON (Javascript Object Notation)
                • supports maps and collections
                • lightweight data-interchange format
              • XML
          • Making calls
            • Unsecured API
              • no authentication required
            • Secure API
              • requires credentials or token
              • sometimes api proxies are used to govern access to an api
              • you can secure an api with different protocols OAuth, SAML and JWT
              • Http Status Codes
                • provides feedback for the outcome of the operation
                • good api should return status codes that align with the http spec
  • Designing APIs
    • Modern API
      • productized
      • easily govern
      • build for consumption – reusable
    • Anypoint Design Center
      • Design your api
      • API Designer
        • Uses RAML
    • AnyPoint Exchange
      • A repository
      • library of assets
      • private content only to available to people in your org
      • when a rest api is added to exchange it creates an api portal
      • Flow Designer lightweight version/ available on the web
      • Anypoint Studio for development
      • Anypoint Management Center
        • version proxy
        • rate limit
        • throttling visibility and
        • control scale your application
      • Runtime Services
        • deploy applications
        • lightweight java-based ESB
        • decouples point to point
        • can be deployed anywhere
        • enforces policies for api governance
      • Anypoint Platform
        • uniquely built
        • deploy anywhere
        • can build your own connector
        • have tons of pre-built connectors
        • implemented all the internal process eg. database connection etc..
      • Achieving Success
        • business outcome
        • org enabled technology
        • delivery
        • Paths
          • Plan for success
          • Establish the foundation
          • Build to scale
          • Measure impact
      • API Notebook
        • on exchange you can create documentation – plays your script
      • MUnit
        • test your mule application
    • Mule Applications
      • can be created visually or through xml
      • under the hood it is java using spring
      • mule apps are deployed to mule runtime
    • Mule Runtime Engine
      • lightweight java ESB and integration platform
      • decouples point to point
      • can be deployed anywhere
      • enforces policies for API governance
    • Mule 4 Applications and flows
      • Mule application receive events, process them and route them
      • A listener listens for events
      • an application can consist of single or multiple flows
      • mule event source
        • initiates the execution of flow
      • mule event processors
        • tranform, filter, enrich
    • Workers
      • dedicated instance of mule that runs the app
      • each worker runs in separate containers from every other application
      • can have different compute power
        • apps can be scaled vertically by change worker size
        • apps can be scaled horizontally by adding more workers
      • there are workers in different environments
  • Accessing and Modifying Mule Events
    • Mule event
      • Mule message – data that passes to the flow
      • attribute – metadata in the header payload – core info of the message
      • variables – metadata for the mule event – can be defined and referenced
  • Structuring Mule Applications
  • Building API Implementation Interfaces
  • Routing Events
  • Handling Errors
  • Writing DataWeave Transformations
  • Using Connectors
  • Processing Records
  • Debugging and Troubleshooting Mule Applications
  • Deploying and Managing APIs and Integrations


Apologies if this is incomplete but will continue to add the materials on the following days.