Mock Mocks in Apex

I love mocking frameworks. I love the ability to isolate a unit of code so I can make smaller, more coherent tests. I have grown accustom to them during my time with java and I would love to use them with apex. The problem is that mocking frameworks rely heavily on robust reflection, a feature apex sorrily lacks.

Sorry. Lost the happy, but the happy's back!
Sorry. Lost the happy, but the happy’s back!

While we cannot yet simply tell a method to generate a mock class, maybe we can make an approximation. A lightweight class that can be substituted for the real thing when testing a class that relies on it could work in many cases. How to get the mock class in there though, that is the question. While Apex is missing most of the necessary reflection, it is not missing all of it. Enter a little known blog, by a man called Jesse Altman, that goes into dependency injection with Apex. That, my friends, is the foundation of what I will go into here. If you didn’t click the link above, and I don’t know why you wouldn’t have, read the article on dependency injection right now. Seriously, if you go on without reading it I will be disappointed in you.

Are you done? And no lying, I will know. So, I have my classes and custom settings pretty much the same as the one from Jesse’s blog post and will be building from there. The best place to start with a blog post on mocks and unit tests is probably a unit test. The unit test will initially test the the classes as they are.

My service just just calls processPayment on a PaymentInterface, nothing special there. The test inserts a custom setting first, grabs the return value from processOrderPayment and verifies the result. Not too much going on here, certainly not deserving a post. Yet. Lets spice this test up.

Look at that, injecting an inner class from within the test worked just fine too. The problem is that this is a trivial example. Why bother mocking? Let’s make this a bit more complex.

I have changed the interface to have the method getAuthCode and added a string parameter to processPayment. The service now checks for a non null authCode and throws an exception if it is. Our mock has had its methods changed accordingly and now, process payment verifies the parameter passed to it. This is closer to our mocks, but now we have a branch we can only test by adding another mock. Inconvenient indeed. One last change, one last push over the finish line. A new class will get us where we need to go.

This hefty class will let us reuse the same mocks multiple times. I wont break this down line for line but I will summarize it. The command object holds parameters to verify against and return values to… return. The method add call adds the call to a map containing a list of command objects, keyed to the method name being mocked. The calls to a particular method must be mocked in the order they will be run. The method getCall gets the command for a method, verifies the parameters are the same and returns the stored return value. What does this look like in practice? Ask, and ye shall receive.

The mock now extends MockMaker and does nothing more than wrap different calls to getCall. The test methods (yes, now there are two) mock out the calls to the payment service with MockMaker.addCall. We can now use the single mock, injected into the OrderService via the factory, to run multiple tests. This isn’t perfect but for services with call-outs or just very heavy methods, this can be a real help.

Looping Slideshow Display With Visualforce and Apex Charting

Anyone ever seen pictures of west-cost start-ups with those TV screens front and center showing some sort of stat or metric? If it is a dev house maybe it is the builds, bugs, & deadlines. A sales firm may have revenue, opportunities and a highlight of recently closed deals. Either way, they are meant to highlight data and allow it to be consumed in a very passive manner, reading it as you pass by. Salesforce makes reports a breeze and dashboards are a snap too. However, what if you wanted to recreate that seamless look, without the tabs, browser UI, or any indication of what is driving the display at all? Sure, there are tons of articles that show you how to get PowerPoint to do that, but using stale data is for suckers. Let’s take a look at what some Apex, Visualforce and JavaScript could do for you.

We should start with the controller.

A good start but missing any real meat. Let’s look at what is there, shall we? Pretty much the only thing in this class so far is a nested wrapper class. This is just a convenient way to get data to the charts. Feel free to do your own thing if this isn’t your style. We better add a way to get some data.

This looks promising! This method grabs all the cases, groups them by priority, then counts the number of cases in those groups. We iterate over that data and toss it into that wrapper object from the prior code block. Add as many of these chunks of code as you want, one for each chart you feel like creating. We are almost done the controller, just one more piece.

This to-the-point bit of code is there to erase the current set of data so it can be refreshed. Remember what I said about stale data being for suckers? This prevents you from being a sucker. Put all of those together and you get a completed controller (mine has a second list of chart data because a one slide slideshow is boring).

On to the Visualforce. We will start off small again and build from there.

This is the base, telling the page to use the ChartController and to not show the header or sidebar. Remember, we don’t want this looking like a webpage or a browser, just a slideshow. Now we need a chart.

This is an apex chart. The width and the height shown here are based on my screen size and layout. If you have extra styling or branding on your slideshow (Trust me, you will want it. The end result of this is bare bones.) you will need to change these values to fit. The apex:chart tag also tells the page what data to use and the id will be used to keep the data fresh. The apex:pieSeries tag tells the page that the data comes from the data field on the wrapper and that the label comes from the name field. There is also the apex:legend tag which provides a legend in the position specified. Finally all of that is wrapped in a div that will provide us the means to allow for movement. Like with the controller, you need one of these for each list of ChartData that you created, just leave the ‘activeSlide’ style off the rest. We still need to code to bring this to life. Let’s begin with the styling first.

Simple stuff here. The ‘side’ class has an absolute position, a white background and is glued to the top left. Every slide has that and therefore, every slide is stacked on top of each other. The slide that also has the ‘activeSlide’ class rises to the top, thanks to its high z-index. To make these slides shuffle, we also need some JavaScript.

First off, I am lazy at times. Seriously, no joke. That is why I included JQuery, because it makes things so darn easy. The next bit sets up a JavaScript method named ‘refreshCharts’ that calls the controller method ‘refreshCharts’ and re-renders my two charts with that data. This is done with the apex:actionFunction tag and will automatically generate the appropriate code. After that, I set up another JavaScript method that will determine the next slide, remove the ‘activeSlide’ class from the currently visible slide, and add it to the next one. To set things in motion, I call that method every 5 seconds and the ‘refreshCharts’ method every 10 minutes. Mix it all together and cook at 350 degrees and your Visualforce should look like this:

What does this look like in action? A chart, then another chart. This is not worth a picture because a still image won’t show it in action and an animated gif can be staged. The best way to see this is to follow along and get this code into any developer account. After you do that, just type in the URL, ‘<YOUR_SALESFORCE_URL>/apex/<YOUR_VISUALFORCE_PAGE_LABEL>’. Tapping F11 should remove all of the browser UI and dragging the mouse to the right side will hide it from view. There you go, a live slideshow. This is the perfect project to dedicate some old hardware to.

Apex Analyzer Dev Diary

Well, this is an interesting situation. When I started this blog, my intent was to do reviews, news, and the occasional small project. My post series on using Heroku to host a personal site was just that. My last post which laid the ground work for an Apex static code analyzer took a good deal of time but would have been fine if it ended there. It didn’t end there though. In fact, I poured a pile more work into it this week to hook together the express framework as well as an sqlite database. If you have been watching the git repo, you have likely noticed…. nothing at all. The changes are so drastic, I cannot commit until I have at least the functionality I had before. No real post this week but I wanted to keep people in the loop.

CLI showing the output of the program

Static Code Analysis of Apex

Would you wander down memory lane with me? It was on one of my first projects at Trifecta that I was introduced to Sonar (now SonarQube), a dashboard that aggregated results from a pile of code analysis tools and presented them in a visually appealing way. I loved the kind of insight it provided.When it listed a bunch of unused methods I went to work pruning them. When it found string concatenation in a big, heavily used loop, I replaced it with StringBuilder. When I moved over to Salesforce, I found a number of solutions but most were either costly or incomplete.

SonarQube dashboard
Different name, same usefulness.

I did manage to find a wonderful blog post, written by Andrew Fawcett, which covered using the tooling API to call out methods that are not referenced anywhere and display it on a Salesforce canvas. This was exactly what I was looking for, or at least it had the potential to be. You see, finding unused methods is a great help once a code-base becomes large and complex enough. Removing these relics could reduce your code-base and may reduce your unit test and deploy time. That is what makes unused method finding, my top feature to have. Even so, I wanted more, and given the choice to extend his project or make my own, I of course made my own.

GitHub new repository button
As if this was even a choice.

I started off with Node.js (bffs 4 lyfe) for no other reason than “I wanted to experiment with it.” Then I reimplemented Andrew’s solution using the node-salesforce module to handle authentication and CRUD operations. Finally, I added a basic plugin system to allow for new checks to be added. How did that all turn out? Let’s find out.

CLI showing the output of the program
Well, it’s a start

I hate to say it, but Node may have been a mistake here. Don’t get me wrong, I had a lot of fun doing this, but there is a fundamental difference between Java and JavaScript that cranked the complexity right up. His logic was very sequential, going through steps one at a time with the next step depending on the completion of the last. Java did this very well, executing each call out to Salesforce and waiting for a response. Anybody familiar with AJAX should start to squirm right about now. I ended up with a tremendous chain of call backs, which fulfilled its purpose but got real messy in a hurry.

Reimplementing this solution went well enough minus the previously mentioned call back avalanche (call-backalanche?), but it was not without its drawbacks. These are no fault of Andrew and merely reflect the incomplete state of the Tooling API. For one thing, the method reference count does not count references in Visualforce. This was inconvenient, but to anyone coming from a java background where missing references in the view is par for course. I also ran into an issue trying this on an org with a scheduled job. You see, to build up the symbol table, it is compiled by basically performing a “check only” deploy. Salesforce did not like that one of the classes the scheduled job relies on was one of the classes we were checking. This resulted in total failure.

The plugins were perhaps the smoothest part of this project. Node’s ability to require a directory and a bit of trickery resulted in a plugin system as simple as dropping a properly constructed JavaScript file in the directory. These are not as efficient as if they were all part of the main file, as they end up looping over the same data a few times, but it is dead simple to add new checks, change thresholds, and disable old checks.

“So, is this project done?” I can hear you asking. The answer is an unequivocal no. On the roadmap is a web based interface, greater structure for plugins, ability to configure for multiple orgs, and heavy work trying out different flows and Node modules before I set in stone how everything will work. Until then, everything is in tremendous flux. Check it out at my GitHub repo.

A Quick Update

Sorry for the lack of post this week. House hunting and the depth of the next post are taking a bit more of my time than I expected. If everything goes as planned, I should have a dozy of a post for next week. While I have your attention, don’t be too surprised if the look and feel of the site changes as well, I am experimenting with new styles. I want to keep things simple but pleasing. See you all then!

Zero to Heroku

From Zero to Heroku in Three Posts, Part 3

Well, we have come a long way, from learning what Heroku was, to hosting a site on it. Now all that is left, are a few minor details. Let’s start by changing that wacky URL to something a bit more appealing.

Domain Name

For this section, unless you are hording domain names like some sort of virtual pack-rat, you will likely have to spend some money. If you have a great aversion to this, fear not, skip to the next section for more freebies. Now that that is out of the way, go buy a domain name. Go on, I can wait, no need to rush this. Once that is done log into the Heroku website, click the name of your app, then click settings. Scroll down to the section that says domains.

Heroku settings
You should be seeing this

On that line, enter the domain you own and click add. Now here is where my tutorial ends and Heroku’s documentation begins. Due to the sheer number of domain registrars, I must refer everyone to Heroku’s custom domain documentation and whatever documentation is published by your domain registrar.

Add-ons

Remember all of those add-ons from the first part? The post you surely read? Well now it is time to add one. This is not a necessity by any means, but it will be good to look through the add-ons and get a feel for how they work. We will start off easy with a simple log viewer. Log into the Heroku website, if you are not still there from the domain setup, click the name of your app, and this time click resources. On that page click Get Add-ons to be taken to the list of Heroku add-ons. You will likely have to click the login button in the top right if this is your first time here. Once that is taken care of, scroll down to the logging sections (section names are along the left hand side) and click Papertrail. I am going with Papertrail out of familiarity, not an endorsement. When I have tried out some of the others, maybe I will do a head-to-head comparison of them. As I was saying, click Papertrail and familiarize yourself with this layout. The add-on pages are set up with a general rundown of what the add-on does at the top and a breakdown of what level of service is offered at each pricing tier. Once you are ready, select the free tier and then select your app from the dropdown at the bottom, finally clicking the add button. Navigate back to your app and click the new Papertrail add-on at the bottom. Hurray, you now have a log viewer at your disposal. Not much use right now, but great if you start to see errors or start doing custom development.

Papertrail logs
All quiet on the website front.

Conclusion

We have come to the end of the opening week, three post blitz. I hope you will stop by every week (I am thinking a Wednesday update schedule would work) to see what I write for all of you.

Zero to Heroku

From Zero to Heroku in Three Posts, Part 2

So you have made it through From Zero to Heroku in Three Posts, Part 1 and you are still here! If you haven’t, it was a 1000ft view of Heroku, the platform we will be working on in this post series. If you already know Heroku, you should be good anyway. Let’s get started with making a personal page. Please note, this tutorial assumes you know how to make a website with HTML, CSS, and Javascript; otherwise this series of posts would become way too broad.

So first thing is first:

  1. Sign up for Heroku! No cost and only a minimum amount of forms to wade through makes this is one low barrier of entry.

    Heroku Sign Up Page
    Single field forms? Yes please!
  2. Grab the Heroku Toolbelt for your operating system. This little command line tool provides a powerful utility for managing your instances.
  3. Download Git if you don’t already have it. This is used to push your changes to Heroku. Due to wide range of options and preferences, I can’t give a one-size-fits-all recommendation. I am going to assume that you can access your Git tool for the command line for the rest of the post.
  4. Download my server app from github. Simply open your command line and navigate to where ever you want to put the folder, then run git clone git@github.com:Bobnix/static-nodeku.git
  5. Navigate to the static-nodeku directory you just created.
  6. Run heroku login and login with your account credentials.
  7. Run heroku create. This will create an instance in heroku and set up the related Git information for you. It will spit out a phrase in the form of WORD-WORD-NUMBER. Take note of this phrase.
  8. Run git push heroku master. This pushes the code from your computer to heroku.

Thats it! You now have a live site, let’s take a look at it by going to https://THE-PHRASE-FROM-STEP-7.herokuapp.com/….

Hello world
Humble beginnings

Well, that is a bit bare. Lets fix that. Because there are so many ways to go about doing this, actually making the site will depend heavily on how you are comfortable working. I personally use Notepad++ or Sublime on windows. Some of the more seasoned may breakout VIM or Emacs. Others may turn to WISIWYG editors. The only rule (for now) is that your site stays contained within the site folder in the server app.

Once you are done with your edits:

  1. Commit your changes by running git add . then git commit -a -m "YOUR MESSAGE HERE"
  2. Run git push heroku master again.
  3. After a few seconds, verify your changes.
Personal page
Now that is more like it

If all goes well, your site should reflect your changes. Keep revising untill you are satisfied, there is no penalty for the indecisive. The third and final post will go into some more optional pieces. If you don’t feel like registering a domain name (that will cost money), feel free to spread the link to where ever you want it to appear.

Zero to Heroku

From Zero to Heroku in Three Posts, Part 1

With Twitter, Facebook, Tumbler, LinkedIn, Instagram, GitHub, StackExchange, MySpace (is MySpace still a thing?) there is a lot of places to put your personal brand. You, dear reader, probably have a few of these yourself. Have you ever wanted a central location you could direct people to, one that linked to all your various identities? Luckily there are solutions, free ones in fact. The one I will be talking about in this series is Heroku, a web host with a unique way to do things.

First off, let’s figure out what Heroku does before we try to harness its awesome power. Something Heroku has no shortage of is the languages it supports. Most hosts support PHP, Python, and Ruby with a few supporting Java. Heroku on the other hand officially supports eight different languages (as of writing) and unofficially supports many more using its buildpack system.

Third Party Buildpacks
If you want to run a server in LISP, who am I to stop you?

Then there are the computational resources, the driving force for your site or app. Instead of having one monolithic app, Heroku encourages you to break your app into compartmentalized processes that it calls dynos. These dynos are split into two categories: web and worker dynos. The web dynos handle incoming requests and are generally what you think of with a webserver. The worker dynos are for performing asynchronous or long running tasks. You see, web dynos are supposed to respond swiftly, taking no longer than 30 seconds to respond to a request. To work around this, heavy lifting should be offloaded to the worker dynos, which have no qualm chewing away at a task for as long as it takes. If you are feeling the strain of a lot of traffic, simply move a slider to gain additional dynos. This is great for a surge after a targeted marketing effort.

Heroku dashboard
This thing goes up past 11

Finally are all the rest of the services that make a server tick. There are a simply dizzying number of add-ons to choose from. Would you like your app to access static documents, cached in memory? Covered! How about send emails and push notifications? Clear to go! Send messages between closely monitored processes for a wildly scalable app? Sure thing! All of these add-ons mean that you and your team can work in the technology that is more comfortable and better suited for the task at hand.

Add ons
Just because you can have MySQL and PostgreSQL doesn’t mean you should.

Phew! So after that advertisement, how in the world does that help you? Well, Heroku sells its services based on the amount of time that you leave your dynos running. You are given 750 free hours a month. Hmm, 31 days in a month max, times 24 hours in a day comes out to 744 hours. What luck, that is just enough to leave one dyno running full time for a month. With that dyno at your disposal, the prospect of a no cost personal site is starting to become clear.

Part II of this series requires git to be installed on your computer and a working knowledge of HTML & CSS.