Uncategorized
Constructor injection, and how it simplifies unit test setup
I’ve recently been reading Growing Object-Oriented Software Guided by Tests (GOOS), and one (of the many) aha moments was a piece of test code that mocked the collaborators and instantiated the object under test – all in the declaration of the test’s private fields. I am particularly fond of this approach for two reasons:
- The test code setup is minimal and easily scanned
- This approach encourages all required collaborators to be passed in through the constructor (aka constructor injection)
I’ve included an illustrative example below using Mockito, the actual test isn’t important but it proves this setup style works.
import org.junit.Test;
public class ItemCheckerTest {
private final ItemFetcher itemFetcher = mock(ItemFetcher.class);
private final Notifier notifier = mock(Notifier.class);
private final ItemChecker itemChecker = new ItemChecker(itemFetcher, notifier);
@Test
public void notifiesStoreManager() throws Exception {
given(itemFetcher.fetch()).willReturn(new FetchedItem());
itemChecker.check();
verify(notifier).notifyStoreManager();
}
...
}
For those unfamiliar with Mockito, the given call stubs a query, while the verify call uses a test spy to check a command call was made.
The important lines are the 3 private member variables of the test class, the first 2 use Mockito’s mock method to instantiate test doubles for our collaborators. The 3rd member variable (itemChecker) is the object under test, you will notice that it is instantiated with both of its required collaborators in the constructor. These 3 lines perform all the wiring we require for our test, without having to resort to @Before methods to set properties.
The reason we can leverage the member variables for this setup is that JUnit creates a new instance of ItemCheckerTest for each of the test methods (@Test). Providing each test with its own set of collaborators ensuring each test runs in isolation.
The most important side effect of setting up the test code in this fashion is that it promotes the use of constructors for wiring up collaborators. Using the constructor for collaborators has a couple of very appealing aspects:
- It becomes impossible to create circular dependencies between your objects
- Your objects are less prone to wiring bugs as they are upfront about their required collaborators.
Why would you want to be upfront about your collaborators, Steve Freeman & Nat Price (GOOS) have this to say:
Partially creating an object and then finishing it off by setting properties is brittle because the programmer has to remember to set all the dependencies. When the object changes to add new dependencies, the existing client code will still compile even though it no longer constructs a valid instance. At best this will cause a NullPointerException, at worst it will fail misleadingly.
Miško Hevery also has a great blog post on constructor vs setter injection.
From zero to headless browser tests in Jenkins
After spending a large portion of the day I can proudly say I have a working set of browser based tests that run on a headless Jenkins install. By headless I mean a server without any physical display installed, as is typical for server machines. This facilitates the execution of high level acceptance tests in much the same fashion as lower level unit and integration based tests, albeit at a slower rate.
The problem I am trying to solve here is a quick feedback loop on acceptance test level behaviour. This blog post will be talking about getting Cucumber scenarios running for a single browser (Firefox). Cross browser testing is a different problem, for which think Sauce Labs would be a better solution as they take the hassle out of provisioning and maintaining a wide range of operating system and browser combinations.
Outlined below are the steps I followed to go from installing Ubuntu server edition through to running the browser based tests (with Cucumber, Capybara, Selenium-Webdriver). You may find some steps are not required on your operating system or for the project you wish to test. Admittedly I dove down a few rabbit holes, but thanks to VirtualBox’s snapshot feature I could safely revert if things turned sour.
- Installing Ubuntu
- Installing Jenkins
- Going Headless
- Installing Ruby with RVM
- Installing Firefox
- Creating a Job
- Bonus Points, watching the browser in realtime
Installing Ubuntu
If you have an existing server you can skip this step. If not grab yourself a copy of Ubuntu Server edition. As I wanted a simple way to play with Jenkins without provisioning hardware I used VirtualBox for virtualisation. I followed the usual VirtualBox installation, however once installed the server showed a blank screen on boot. This was fixed by following the workaround on the Ubuntu forums.
When installing, it is handy to enable the OpenSSH server so you can SSH onto the box from your desktop terminal, this makes copy & pasting some of the later steps much easier. To make the VirutalBox server visible on the network, change the network mode from NAT to bridged.
Installing Jenkins
Installing Jenkins is a breeze, as debian packages have been set up, check the wiki page for details.
$ sudo vi /etc/apt/sources.list.d/jenkins.list
Add "deb http://pkg.jenkins-ci.org/debian binary/"
$ sudo apt-get update
$ sudo apt-get install jenkins
This automatically creates an account called jenkins. We will need to login as this user later so set a password for jenkins with:
You should now be able to view the Jenkins dashboard at http://your.server:8080/
Going Headless
Now that Jenkins is installed, we want to get a headless display configured for our browser based tests. First up hit Manage Jenkins > Manage Plugins > Available and install the Hudson Xvnc plugin (this works with Jenkins despite its name). Schedule Jenkins to restart to pickup the plugin. Once installed this gives us the ability to start a headless display automatically when we configure our jobs, more on that later.
With Jenkins configured we need to ensure the required software is installed on the server:
vncserver requires a password to be set before it can be used, this needs to be set before Jenkins can make use of the vncserver. For this we need to switch to the jenkins user and set a password.
$ vncserver
Enter a password, and verify it
$ vncserver -kill :1 # or whichever display the vncserver output mentioned
When Jenkins runs it doesn’t need to know this password, but if you want to watch a running job you can connect to the running vnc session with that password and watch the tests in real time.
I initially headed down the Xvfb route but that seemed to require a lot of custom configuration in the job’s build script and isn’t related to the Xvnc plugin.
Installing Ruby with RVM
The job I’m wanting to run is a set of acceptance tests written in Cucumber with automation done using Capybara (Selenium-Webdriver under the hood). So its a Ruby job, and all good Ruby jobs use RVM. Fortunately RVM has a page on integrating with Hudson/Jenkins. I followed the recommended steps and installed RVM for a single user (jenkins).
$ sudo -Hiu jenkins
$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
Once RVM is configured, run rvm notes to find the full list of dependencies you need to install for your required version of Ruby. e.g.
$ rvm notes
$ sudo apt-get install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev
Note that I didn’t give the jenkins user sudo rights, so I installed all packages through my usual admin account on the server.
RVM can be configured to allow the automatic installation of Ruby versions and gemsets by adding the following to ~/.rvmrc for the jenkins user:
rvm_project_rvmrc=1
rvm_gemset_create_on_use_flag=1
Installing Firefox
Of course, a headless server isn’t any good without a browser to test
This is the default browser that selenium will select.
Creating a Job
At this point the Jenkins server should be fully configured to run headless jobs, so lets dive in and create one. Create a new freestyle job. Notice there is a new option available under the ‘Build Environment’ section call ‘Run Xvnc during build’, check this to have the plugin automatically do its magic.
For my example, I didn’t bother with checking projects out source control, I simply created a project in the /tmp directory. You’ll want to enable the appropriate SCM plugin and configure a checkout.
Under the build section add an Execute shell step with the following:
cd /tmp/selenium-test
source "$HOME/.rvm/scripts/rvm"
[[ -s ".rvmrc" ]] && source .rvmrc
bundle install
cucumber
The -e flag in #!/bin/bash -e ensures the script stops after any errors.
You will notice that the script sources the .rvmrc file directly for the project, this ensures the correct version of Ruby is used with a gemset appropriate for your project. My .rvmrc looked something like:
Calling bundle install automatically installs bundler, reads the Gemfile.lock and installs all required gems. Finally cucumber kicks off the actual cucumber scenarios, and fingers crossed, they should pass with flying colours.
In order to keep happy customers
As a developer I want to ensure all my features continue to pass on CI
Scenario: Headless browser
When I check the nets without a head
Then I the nets should be readable
1 scenario (1 passed)
2 steps (2 passed)
0m7.975s
Terminating xvnc.
$ vncserver -kill :33
Killing Xvnc4 process ID 6873
Finished: SUCCESS
Bonus Points, watching the browser in realtime
As the headless display is running in vncserver, you can connect to the vnc session and watch the tests run in real time. Just use your regular VNC client and connect to your.server:59xx where xx is the display number output on the Jenkins console for the running job. You will need to enter the password you set the first time you ran vncserver.
[Note: most/all of these instructions should work with Hudson also]
Subscribe
Recent Posts
Tags
- "Sorry, no matches found for “tdd” near Auckland, New Zealand" http://t.co/Ahc736MX #auckland #whowantstostartonewithme 2 weeks ago
- Great series on the SOLID design principles for JavaScript http://t.co/ELoPuOH2 2 weeks ago
- Auckland devs, what meetups should I be attending? #java #groovy #ruby #javascript #bdd #tdd 2 weeks ago
- More updates...
