Why I think unit testing is the basis of any solid automation strategy

In a recent blog post I talked about why and how I still use the test automation pyramid as a model to talk about different levels of test automation and how to combine them into an automation strategy that fits your needs. In this blog post I’d like to talk about the basis of the pyramid a little more: unit tests and unit testing. There’s a reason -or better, there are a number of reasons- why unit testing forms the basis of any solid automation strategy, and why it’s depicted as the broadest layer in the pyramid.

Unit tests are fast
Even though end-to-end testing using tools like Selenium is the first thing a lot of people think about when they hear the term ‘test automation’, Selenium tests are actually the hardest and most time-intensive to write, run and maintain. Unit tests, on the other hand, can be written fast, both in absolute time it takes to write unit test code as well as relative to the progress of the software development process. A very good example of the latter is the practice of Test Driven Development (TDD), where tests are written before the actual production code is created.

Unit tests are also fast to run. Their run time is typically in the milliseconds range, where integration and end-to-end tests take seconds or even minutes, depending on your test and their scope. This means that a solid set of unit tests will give you feedback on specific aspects of your application quality much faster than those other types of tests. I stressed ‘specific aspects’, because while unit tests can cover ground in relatively little time, there’s only so much they can do. As goes for automation as a whole.

Unit tests require (and enforce) code testability
Any developer can tell you that the better structured code is, the easier it is to isolate specific classes and methods and write unit tests for them, mocking away all dependencies that method or class requires. This is referred to as highly testable code. I’ve worked in projects where people were stuck with badly testable code and have seen the consequences. I’ve facilitated two day test automation hackathon where the end goal was to write a single unit test and integrate it into the Continuous Integration pipeline. Writing the test took ten minutes. Untangling the existing code so that the unit test could be written? Two days MINUS ten minutes.

This is where practices like TDD can help. When you’ve got your tests in place before the production code that lets the tests pass is written, the risk of that production code becoming untestable spaghetti code is far lower. And having testable code is a massive help with the next reason why unit testing should be the basis of your automation efforts.

Unit tests prevent outside in test automation (hopefully)
If you’re code is testable, it means that it’s far easier to write unit tests for it. Which in turn means that the likelihood that unit tests are actually written increases as well. And where unit tests are written consistently and visibly, the risk that everything and its mother it tested through the user interface (a phenomenon I’ve seen referred to as ‘outside-in test automation’) is far less high. Just writing lots of unit tests is not enough, though, their scope, intent and coverage should be clear to the team as well (so, testers, get involved!).

Unit tests are a safety net for code refactoring
Let’s face it: your production code isn’t going to live unchanged forever (although I’ve heard about lines of COBOL that are busy defying this). Changes to the application, renewed libraries or insights, all of these will in time be reason to refactor your existing code to improve effectivity, readability, maintainability or just to keep things running. This is where a decent set of unit tests helps a lot, since they can be used as a safety net that can give you feedback about the consequences of your refactoring efforts on overall application functionality. And even more importantly, they do this quickly. Developers are humans, and will move on to different tasks if they need to wait hours for feedback. With unit tests, that feedback arrives in seconds, keeping them and you both focused and on the right track.

In the end, unit tests can, will and need not replace integration and end-to-end tests, of course. There’s a reason all of them are featured in the test automation pyramid. But when you’re trying to create or improve your test automation strategy, I’d advise you to start with the basis and get your unit testing in place.

By the way, for those of you reading this on the publication date, I’d like to mention that I’ll be co-hosting a webinar with the folks at Testim, where I’ll be talking about the importance of unit testing, as well as much more with regards to test automation strategy. I hope to see you there! If you’re reading this at a later date, I’ll add a link to the recording as soon as it’s available.

On crossing the bridge into unit testing land

Maybe it’s just the people and organizations I meet and work with, but no matter how active they’re trying to implement automation and involve testers therein, there’s one bridge that’s often too far for those that are tasked with test automation, and that’s the bridge to unit testing land. When asking them for the reasons that testers aren’t involved in unit testing, I typically get one (or more, or all) of the following answers:

  • ‘That’s the responsibility of our developers’
  • ‘I don’t know how to write unit tests’
  • ‘I’m already busy with other types of automation and I don’t have time for that’

While these answers might sound perfectly reasonable to some, I think there’s something inherently wrong with all of them. Let’s take a look:

  • With more and more teams becoming multidisciplinary, we can’t simply shift responsibility for any task to a specific subgroup. If ‘we’ (i.e., the testers) keep saying that unit testing is a developer’s responsibility, we’ll never get rid of the silos we’re trying to break down.
  • While you might not know how to actually write unit tests yourself, there’s a lot you CAN do to contribute to their value and effectiveness. Try reviewing them, for example: has the developer of the unit test missed some obvious cases?
  • Not having time to concern yourself with unit testing reminds me of the picture below. Really, if something can be covered with a decent set of unit tests, there really is no need to write integration or even (shudder) end-to-end tests for it.

Are you too busy to pay attention to unit testing?

I’m not a devotee of the test automation pyramid per se, but there IS a lot of truth to the concept that a decent set of unit tests should be the foundation of every solid test automation effort. Unit tests are relatively easy to write (even though it might not look that way to some), they run fast (no need for waiting until web pages are loaded and complete their client-side processing, for example..) and therefore they’re the best way to provide that fast feedback that development teams are looking for those in this age of Continuous Integration / Delivery / Deployment / Testing / Everything / … .

To put it in even bolder terms, as a tester, I think you have the responsibility of familiarizing yourself with the unit testing activities that your development team is undertaking. Offer to review them. Try to understand what they do, what they check and where coverage could be improved. Yes, this might require you to actually talk to your developers! But it’ll be worth it, not just to you, but to the whole team and, in the end, also to your product and your customers. Over time, you might even write some unit tests yourself, though, again, that’s not a necessity for you to provide value in the land of unit testing. Plus, you’ll likely learn some new tricks and skills by doing so, and that’s always a good thing, right?

For those of you looking for another take on this subject, John Ruberto wrote an article called ‘100 percent unit test coverage is not enough‘, which was published on StickyMinds. A highly recommended read.

P.S.: Remember Tesults, the SaaS solution for storing and displaying test results I wrote about a couple of months ago? The people behind Tesults recently let me know they now offer a free forever plan as well. So if you were interested in using their services but could not afford or justify the investment, it might be a good idea to check their new plan out here. And again, I am in no way, shape or form associated with, nor do I have a commercial interest in Tesults as an organization or a product. I still think it’s a great platform, though.

An approach to test your user interface more efficiently

As returning readers of this blog might have read before, I am pretty skeptical about writing automated tests that interact with the application under test at the user interface level. These UI tests tend to be:

  • slow in execution, since they are typically end-to-end tests from an application-layer perspective, and
  • demanding when it comes to maintenance, because the user interface is typically a part of an application subject to frequent changes.

However, the user interface often is an important component of an application and therefore it requires testing effort. Since this blog is all about test automation, I’d like to talk about a different approach to user interface test automation in this blog post.

But first, let me explain a subtle yet important difference. On the one hand, there’s testing the user interface. Here, the actual logic incorporated in the user interface is isolated and tested as a unit. Everything that’s happening ‘behind’ the user interface is out of scope of the test and therefore usually mocked. On the other hand, there’s testing application logic through the user interface. This is generally done using tools such as Selenium. This type of automated tests uses the user interface as its point of entry and validation, even though the actual logic that processes the input and generates the output to be checked is not implemented at the user interface layer at all.

Testing the user interface versus testing through the user interface

Now, only when you specifically want to perform end-to-end application tests, or when there really isn’t any other option than to use the user interface drive tests that validate underlying application logic should you resort to tools such as Selenium. In all other cases, it might be a better idea to see if there’s a better option available.

User interface architectures and testability
In the remainder of this post I want to zoom in on a commonly used user interface pattern, namely Model-View-ViewModel, or MVVM in short, and what I think is a suitable approach for writing automated tests for user interfaces adhering to this pattern.

MVVM explained (briefly)
The MVVM pattern lets you separate presentation logic (that defines what information is shown on the screen) from the actual presentation (that defines how the information is displayed). Schematically, the pattern looks like this:

A schematic representation of the Model-View-ViewModel pattern

The View is the user interface, which is made up of textboxes, labels, buttons, etc. It is responsible for defining the structure, layout and appearance of what you seen on the screen. The Model is an implementation of the domain model. It consists of a data model along with business rules and validation logic. The View Model is the intermediary between the View and the Model, handling user interface actions (such as the click of a button) and interacting with models usually by invoking methods in the model classes (for example to update a record in a database). It is also responsible for presenting data from the model (for example the results of a query) to the view in a representation that can be easily displayed on screen.

One of the key ideas behind MVVM and other user interface architectures, such as Model-View-Controller (MVC) and Model-View-Presenter (MVP), is that the separation of concerns ingrained in these architectures makes them testable using unit tests, instead of having to rely on expensive and slow end-to-end tests.

Testing user interfaces built on MVVM
Since all business logic is contained in the view model, it makes sense to make it the center of attention for our testing efforts. Since view models are implemented as classes in object orientedn languages these tests are usually defined as unit tests. This immediately shows the value of asking yourself ‘am I testing the user interface or merely testing my application through the user interface?’. In case of the former, writing complicated, slow and brittle end-to-end tests with tools such as Selenium is pure overkill.

Instead, we write a simple unit test that covers the business logic in the view model. We mock the model part, since business and implementation logic further down the application stack can be tested using (again) unit tests, or when the view model for example invokes web services for storing, processing and retrieving data, we can write API-level tests to cover that part of our application. The view part can – when MVVM is applied correctly – be left out of scope, since buttons, labels and text boxes are usually standardized objects that ‘only’ need to be positioned correctly on screen (in reality, designing good user interfaces is a respectable and skillful job of it’s own, no disrespect intended). If you really want to write checks to verify that the view part is implemented correctly, there’s always tools such as Galen Framework that allow you to check your user interface at the design level (i.e., visual checks).

Links to example implementations and tests
Rather than writing my own example here, I’d like to link to some well-written and understandable examples of the application of MVVM and the way you can write unit tests for your MVVM-based user interface here. I’m currently in the early stages of implementing a suitable testing approach for the user interface of the key application at my current project, so you can expect some real-life examples from my own hand in a future post. For now, I encourage you to take a look at the following blog posts and examples: