Applying software design patterns to your test automation code

Yes, yes, yes… The creation of automated checks as a means of supporting and speeding up parts of the software development and testing process (a concept better known as ‘test automation’) should be considered software development. I’ve mentioned that a couple of times on this blog already, and today I’m doing it again. In this post, I’d like to take a look at why it’s probably a good idea to apply good software design patterns to your test automation code. Before I ramble on, please take note that I deliberately don’t call these patterns ‘best practices’. This is because sticking the ‘best practice’ label onto a software development pattern or habit usually promises something that that pattern cannot live up to. For each ‘best practice’, there’s at least one situation (but usually a lot more) where this practice just isn’t the best one to be applied. So, instead of ‘best practice’ it should be called ‘best practice for situations X and Y, but not for situation Z’. Or ‘best practice, but only on a Tuesday’. Instead, I think it’s best just to steer clear of the term altogether.

With that personal gripe out of the way, let’s look at why I think you should make use of proven software design and implementation patterns to improve your test automation code. Basically, it comes down to three aspects: maintainability, maintainability and .. maintainability. Applying patterns will not improve the quality and effectiveness of your checks, but it will do wonders for what probably is the most time-consuming task in test automation: maintaining the test code to ensure that it stays fresh, up to date and, well, running. Code that does not follow any basic software design patterns is likely to require much more effort to be read, understood and maintained. This is especially the case when you’re the lucky guy or girl who’s assigned the task of maintaining test code that you didn’t write yourself, but I definitely wouldn’t rule out the chance that you return to your own badly written test code after a couple of weeks and start thinking ‘what the … was THAT supposed to do again?’.

So, in short, you should apply good design and implementation patterns and practices. Here are some of the most common ones.

Don’t Repeat Yourself (DRY)
Being the opposite of WET (Write Everything Twice), DRY states that ‘Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.’ Or, as I like to explain DRY with regards to test automation, if any change to your application under test requires you to make the same change twice in your test code, you’re doing it wrong. Any object on any level in your test code (from a single constant all the way up to a sequence of actions required to simulate a certain business process) should be defined exactly once. Some test automation-related examples of the DRY pattern in action are:

  • The use of constants classes for anything from default timeout values to database connection strings – update once, effective everywhere
  • The Page Object pattern in Selenium – all elements, actions and checks related to a certain page or part of a page are defined in a central spot: the Page Object
  • The use of Examples in your Cucumber specs – A scenario is written once and then repeated multiple times with different input and validation values

DRY - Don't repeat yourself

Keep It Simple, Stupid (KISS)
While the DRY principle is probably the best known in software development, I think the KISS principle is just as important and just as (if not more) effective when it comes to maintainability of your test automation code. In my own words, this principle states that the solution that is easiest to implement is almost always the best one. Therefore, no matter what the problem is, you should always strive for the simplest solution possible. Some examples with regards to test automation:

  • Use predefined libraries instead of writing your own solutions. I’ve been guilty of this myself as well. For example, I still receive comments on this post regarding creating your own HTML reports for Selenium tests, even though I’ve since discovered and written multiple times about ExtentReports, a predefined library that does everything you want and more. No maintenance needed, just import it and you’re ready to go. This saves you a lot of unnecessary code to maintain as well.
  • Don’t automate everything in sight. Automating something just because you can or because your manager or (even worse) a senior test automation engineer (who should know better) is a recipe for disaster. I’m currently writing another blog post (one that will probably end up on LinkedIn Pulse rather than this blog) on why you should first ask the ‘why’, then the ‘what’, and then finally the ‘how’. This will save you from writing and maintaining a lot of useless checks, which in turn makes your solution a lot simpler.

KISS - Keep It Simple, Stupid

Choose a proper naming convention and stick to it
The last pattern that I think should definitely be applied to test automation code – or even better: to all related artifacts – is the use of a proper naming convention. I don’t really have a preference to a specific naming convention (although it took me a while to get used to C# methods starting with an uppercase character with me coming from Java), but picking one and sticking with it has definite benefits:

  • Assuming you’ve picked a naming convention that requires you to use descriptive names for your variables and methods (forget any convention that does not do this), using one and the naming convention everywhere keeps your code readable to anyone involved. By this, maintainability is also improved since it should be clear from the names used what a specific variable or method is actually representing or doing.
  • Using proper naming (and structuring) conventions for files and folders allows anybody on your team to locate that one pesky file or test automation report that’s being requested.

Use a proper naming convention

Start from the get go
To ensure that your test automation code remains readable and maintainable, you should apply good software design patterns from the very first line of code onward. Even if you’re just writing a little script to set up some test data or to perform a short and quick end user routine, you never know what those five lines of code will grow into one day. With code, it’s a bit like with pavements: it’s easy to leave behind rubbish when someone before you has done the same. However, when the pavement (or the code) is spotless, you’ll probably feel bad about leaving behind any trash after you’ve paid a visit. Always keep in mind that refactoring and improving badly written code is something no developer likes to do.

Be pragmatic
Of course, as with so many other things in life, applying patterns isn’t a case of black or white. It might not make sense to apply patterns to throw-away code (code that’s only used once). Also, with regards to the DRY principle, there’s such a thing as too DRY code. In general, though, applying good software design patterns will definitely benefit your code and those who rely on or need to work with it. As I said at the beginning of this post, test automation is software development. Let’s start treating it as such.

Lessons learned from delivering a test automation workshop

As I’ve shared in a recent post, I am looking to move away from doing (only) billable-by-the-hour work and towards providing value-based services. One example of such a service would be the development and delivery of workshops related to the test automation craft and specific test automation tools. Last week (May 11th) I was given the opportunity to host a workshop on testing RESTful web services with REST Assured before a group of around 25 members of TestNet, one of the oldest and largest Dutch testing communities. In this post, I will share my experiences and some of the lessons I’ve learned with you.

Contents of the workshop
The intention of the workshop was to give the participants an introduction to RESTful web services in general, as well as to REST Assured as a test automation tool and the features it provides to write tests for these web services. If you’d ask me to provide a table of contents for the workshop, it would look something like this:

  1. Introduction to RESTful web services (concepts and application)
  2. Introduction to REST Assured (installation, features, writing a first test)
  3. Basic header and body validations
  4. Parameterization of tests
  5. Handling various types of authentication
  6. Parameter passing
  7. Integration into build and CI processes

Steps 3 through 6 were all followed by a number of practical exercises that allowed the participants to start writing their own REST Assured tests. It wouldn’t be a workshop if the participants wouldn’t have had the chance to get their hands dirty!

Delivering the workshop

Delivering the workshop – Picture courtesy of @autotestersara

Lessons learned: preparing the workshop
Of course, there would be no workshop (or at least not a workshop I could deliver with confidence) without good bit of preparation. Although I had given a workshop on RESTful web service testing before, most of the content for this workshop was brand new. This means I needed quite some preparation time to create the slides, the exercises, a runnable demo project that contained the exercises and their solutions and the installation and configuration instructions for the participants.

From my experience with training and workshop delivery I knew that setting up participants’ machines can be a real bottleneck. To try and circumvent this I wrote fairly detailed instructions on how to setup a machine for the workshop. Note that I wasn’t in the position to provide the participants with fully prepared laptops as this was a fairly open and casual conference. Also, as a freelancer, I don’t have the budget to keep a bunch of laptops in stock, nor do I particularly want to do so. In a previous workshop I tried to supply the participants with virtual machines that had everything preinstalled, but that approach did come with problems of its own. Let’s say I’ve found out the hard way that virtual machine do not behave the same on different platforms..

Some tips and takeaways concerning workshop preparation:

  • Expect at least half the participants to NOT prepare for the workshop. Possible solution: have the ones that forgot or didn’t have the time pair with those that did follow the instructions. Additional bonus: this increases interaction within the group. Note that it’s not a good idea to have them spend the first half hour (or more) of the workshop itself to complete the installation instructions. This uses up valuable workshop time and can be annoying for the participants that did prepare as requested.
  • Have enough material to fill the entire workshop, then prepare 50% more. Since it’s often hard to estimate the experience and skills of your audience, it’s a good thing to be on the safe side and have enough backup material at hand in case the participants breeze through the first part of your exercises.
  • If you’re delivering a technical workshop, be sure to have some alternatives to technological dependencies at hand. In my case, the public API we used for the exercises was down. Having alternatives ready ensures that the workshop does not come to a grinding halt at the first bump in the road.

Lessons learned: delivering the workshop
After all preparation has been done, it’s showtime: time to deliver the goods to your audience. For me, this is the fun part, but also the part that’s most nerve-wracking. Especially the first couple of minutes, where you need to find your rhythm and pace as well as get to know your audience. The big lesson here is that with proper preparation, delivering your workshop should be fun. I always try and remind myself once or twice during the workshop that having fun is a big part of a successful workshop. Not only for yourself, but when you have fun, your enthusiasm will likely rub off on the participants as well.

Some tips and lessons learned concerning workshop delivery:

  • Ask questions to your audience. Of course, participants should be allowed to ask questions whenever they arise, but asking questions yourself is a great way to increase interaction.
  • Be sure to send any slides, documentation and code samples to the participants afterwards. It gives them something tangible to take home and review, as well as show to their peers or managers. Stick your name on it (subtly) so other people viewing the material know your name. Be generous and share, it will come back to you in the future. It might be a good idea to provide slides in a readonly format such as PDF, though.
  • Be sure to drink enough (water, that is). When you’re talking a lot, your mouth will start to get dry which makes it harder to talk clearly. I’ve experienced that this is somehow especially the case when talking in a language that’s not your mother tongue (for example English in my case). Strange, but true…
Students at work at the workshop

Students at work at the workshop – Picture courtesy of @autotestersara

Feedback
Personally, I felt my workshop went pretty well. Even though most participants did not have a specific background in test automation, from what I’ve heard every participant took away at least some new knowledge. That defines ‘mission accomplished’ for me. Especially nice was that some participants pointed out things that could be improved further. Getting this type of feedback has two distinct benefits:

  • You can use these suggestions to improve future workshops, obviously, but also:
  • The fact that you’re receiving these suggestions is an indicator that your audience is listening and engaged (with the amount and quality of the questions asked being another such indicator).

I hope me sharing all of the above is somehow useful to anyone involved in delivering technical workshops. Maybe it even motivates you to start looking into giving workshops and training yourself! If so, please do let me know, I love talking motivation, topics and techniques with fellow teachers. In the meantime, for all of you aspiring to get into delivering workshops and technical training yourself, I cannot recommend this episode from the Freelance Transformation Podcast enough.

Oh, and in case you’re interested in me giving a test automation-related workshop in your organization, please do let me know as well! You can contact me through the contact page.

I have some conference workshop proposals lined up, as well as some decent leads obtained at the same conference after the workshop, so here’s to hoping that there will be more lessons learned on technical workshops in the future!

Creating data driven API tests with REST Assured and TestNG

As you’ve probably read in previous posts on this site, I am a big fan of the REST Assured library for writing tests for RESTful web services. In this post, I will demonstrate how to create even more powerful tests with REST Assured by applying the data driven principle, with some help from TestNG.

Combining REST Assured and TestNG
REST Assured itself is a DSL for writing tests for RESTful web services and does not offer a mechanism for writing data driven tests (i.e., the ability to write a single test that can be executed multiple times with different sets of input and validation parameters). However, REST Assured tests are often combined with JUnit or TestNG, and the latter offers an easy to use mechanism to create data driven tests through the use of the DataProvider mechanism.

Creating a TestNG DataProvider
A TestNG DataProvider is a method that returns an object containing test data that can then be fed to the actual tests (REST Assured tests in this case). This data can be hardcoded, but it can also be read from a database or a JSON specification, for example. It’s simply a matter of implementing the DataProvider in the desired way. The following example DataProvider creates a test data object (labeled md5hashes) that contains some example text strings and their md5 hash:

@DataProvider(name = "md5hashes")
public String[][] createMD5TestData() {
		
	return new String[][] {
			{"testcaseOne", "4ff1c9b1d1f23c6def53f957b1ed827f"},
			{"testcaseTwo", "39738347fb533d798aca9ae0f56ca126"},
			{"testcaseThree", "db6b151bb4bde46fddb361043bc3e2d9"}
	};
}

Using the DataProvider in REST Assured tests (with query parameters)
Using the data specified in the DataProvider in REST Assured tests is fairly straightforward. In the example below, we’re using it in combination with a RESTful web service that uses a single query parameter:

@Test(dataProvider = "md5hashes")
public void md5JsonTest(String originalText, String md5Hash) {
		
	given().
		parameters("text", originalText).
	when().
		get("http://md5.jsontest.com").
	then().
		assertThat().
		body("md5", equalTo(md5Hash));
}

Notice how the data in the DataProvider can be used for specification of expected results just as easy as for specifying input parameters. When we run this test, we can see in the output that the test is run three times, once for every set of input and validation parameters:

Console output for our data driven REST Assured test

Using the DataProvider in REST Assured tests (with query parameters)
The other parameter approach commonly used with RESTful web services is the use of path parameters. Let’s create another DataProvider, this one specifying Formula 1 circuits and the country they are situated in:

@DataProvider(name = "circuitLocations")
public String[][] createCircuitTestData() {
		
	return new String[][] {
			{"adelaide","Australia"},
			{"detroit","USA"},
			{"george","South Africa"}
	};
}

The Ergast Developer API provides motor racing data through a public API (check it out, it’s really cool). Here’s how to parameterize the call to get specific circuit data and check the country for each circuit with REST Assured, again using our DataProvider:

@Test(dataProvider = "circuitLocations")
public void circuitLocationTest(String circuitId, String location) {
		
	given().
		pathParameters("circuitId",circuitId).
	when().
		get("http://ergast.com/api/f1/circuits/{circuitId}.json").
	then().
		assertThat().
		body("MRData.CircuitTable.Circuits[0].Location.country",equalTo(location));
}

The only real difference is in how to set up path parameter use in REST Assured (see also here), otherwise making your tests data driven is just as easy as with query parameters.

When we run this second test, we can see again that it’s run three times, once for every circuit specified:

Console output for our data driven REST Assured test (with path parameters_

A Maven Eclipse project containing the code demonstrated in this blog post can be downloaded here.