Skip to main content

Testing-in-the-Trenches: Spin-off a New Class

Testing in the Trenches (TinT) is an occasional series based on my experiences promoting and coaching Unit Testing on real projects, ones where the team or management do not always embrace the philosophy or practices of Unit-Testing.

Technique: Spinning-off a New Class

Imagine you believe in the principles of automated unit testing. You want to write tests to prove the correctness of your code.
But imagine that you are working in a code base with pockets, sections, even whole packages of code that has no tests, possibly even code whose design is hostile to being put into a test harness.
Imagine that the enhancement or bug fix on your plate involves changing existing code that has no current test coverage, or not very much, or maybe some tests but they are poor quality. Maybe they have a lot of dependencies, or it takes a lot of work to set them up, or they do too many things on construction.
This imaginary scenario is very common on some projects.

Faced with such a scenario, as practitioners of the craft of unit-testing, we want to at the very least provide tests that cover our new code. We want to ensure that, when we add code for an enhancement or bug fix, our contribution is unit-tested.


One effective technique is to separate our new code into a new class. Like a TV show that spins-off from another one, we want to spin-off our new work into a new class, one that the original class will call for our new fix or feature. The idea is to put your changes into the new class and use it from the original class.

This testing technique has some immediate Advantages:

1. it lets us clearly separate our new code from the old code;
2. it lets us define a clean, clear interface between the old class and the new one;
3. our new code becomes much easier to test;
4. it is a smaller, less invasive change to the existing class than stuffing all our changes into it.

It is a technique that is not without controversy, of course. Some Disadvantages:
1. while it does less violence to the old class, it potentially does violence to the overall design - if there was a coherent story to the design before, it may now have become a little more muddled;
2. moving new functions into new classes and away from the existing abstractions can increase local and overall system complexity;
3. it leaves the issue of the existing untested code and its challenges for another day, punting that concern into the future.

Here is a real-world (redacted) example. On one project some years ago, a feature of our product allowed users to save the output of a process to a file. The existing business rule was that, for security reasons, the file would be created in a specific, hard-coded location. Then the requirement changed: they would be able to write the file to different locations, but any possible locations would be restricted to paths under a given root folder, which would be defined in another part of the application by a user with Administrator privileges.

(1) The first step in this Spin-off Class technique is to identify where in the original code the changes need to be made.

In the case of my enhancement, I found the place where the output-generator accessed the original, hard-coded output location. It would need to change, to get the location in a different way. I also found the bigger and more interesting change: the UI screen from which the action is triggered. It would need a way to identify the user's preferred output location. Something needed to change here as well - a button that opened a JFileChooser dialog, and some ability to process its results.

(2) The second step is to think through the detailed design of the new class and its fields and methods that will perform the new work.

In my case, I was adding a Browse button for the users to browse to their destination folder. The team culture was to build Action Handlers as private internal classes within the form or screen on which it appeared. But with an eye toward both testability and reusability, I wanted to pull this new function out into a separate public class.
It needed a good name, something like BrowseActionWithFixedRootFolder - a bit long and awkward, but seemed to communicate its purpose. It needed to live in an appropriate package, so I chose the com.appname.file package since it would deal with folder selections.
Since it would sub-class an Action class, some of its API, such as actionPerformed() was easy to design. But I needed to design how the selected file folder would be communicated back from the JFileChooser, through this new class, and back to the calling class.
Since I was designing this new class to be reusable, I needed to design a way to tell the action what to do with a file or folder once one was selected. Inspiration came, in my case, from existing design patterns.
Since I wanted this action class to be reusable in other contexts, I needed to design how it will know what was the fixed root, the starting point of the folder structure. These and a handful of other considerations shaped the fields and the method parameters of the new class.

(3) The third step is to implement the detailed design of the new class.

With a well-thought-out design, this step was straight-forward. I could create my Action class and write the unit-tests to cover this new functionality.

(4) The final step is to change the original class to call your new class.

The original class remained as hard as ever to test, and in this project I attempted no refactoring to get the original class into the test harness. In my case, I was adding a new button and this new Action class, so the impact on the original class was as minimal as possible. Some manual acceptance testing indicated that the UI worked as expected. My suite of new unit tests validated the rest of the behavior of the Action and the class to which I delegated the responsibility to handle the selected folder which, in my requirements, meant validating that it was a sub-folder of the fixed root folder, and then communicating the selected path to the process that would produce the output file.

Making BrowseActionWithFixedRootFolder into a new class pushed me to better design, as the code is reusable and the methods are more accessible for tests. This then let me complete my enhancement, if not with 100% coverage, at least with a high degree of coverage, including the most substantive parts.

Popular posts from this blog

How to do Git Rebase in Eclipse

This is an abbreviated version of a fuller post about Git Rebase in Eclipse. See the longer one here : One side-effect of merging Git branches is that it leaves a Merge commit. This can create a history view something like: The clutter of parallel lines shows the life spans of those local branches, and extra commits (nine in the above screen-shot, marked by the green arrows icon). Check out this extreme-case history:  http://agentdero.cachefly.net/unethicalblogger.com/images/branch_madness.jpeg Merge Commits show all the gory details of how the code base evolved. For some teams, that’s what they want or need, all the time. Others may find it unnecessarily long and cluttered. They prefer the history to tell the bigger story, and not dwell on tiny details like every trivial Merge-commit. Git Rebase offers us 2 benefits over Git Merge: First, Rebase allows us to clean up a set of local commits before pushing them to the shared, central repository. For this

Java 8: Rewrite For-loops using Stream API

Java 8 Tip: Anytime you write a Java For-loop, ask yourself if you can rewrite it with the Streams API. Now that I have moved to Java 8 in my work and home development, whenever I want to use a For-loop, I write it and then see if I can rewrite it using the Stream API. For example: I have an object called myThing, some Collection-like data structure which contains an arbitrary number of Fields. Something has happened, and I want to set all of the fields to some common state, in my case "Hidden"

Git Reset in Eclipse

Using Git and the Eclipse IDE, you have a series of commits in your branch history, but need to back up to an earlier version. The Git Reset feature is a powerful tool with just a whiff of danger, and is accessible with just a couple clicks in Eclipse. In Eclipse, switch to the History view. In my example it shows a series of 3 changes, 3 separate committed versions of the Person file. After commit 6d5ef3e, the HEAD (shown), Index, and Working Directory all have the same version, Person 3.0.

Code Coverage in C#.NET Unit Tests - Setting up OpenCover

The purpose of this post is to be a brain-dump for how we set up and used OpenCover and ReportGenerator command-line tools for code coverage analysis and reporting in our projects. The documentation made some assumptions that took some digging to fully understand, so to save my (and maybe others') time and effort in the future, here are my notes. Our project, which I will call CEP for short, includes a handful of sub-projects within the same solution. They are a mix of Web APIs, ASP MVC applications and Class libraries. For Unit Tests, we chose to write them using the MSTest framework, along with the Moq mocking framework. As the various sub-projects evolved, we needed to know more about the coverage of our automated tests. What classes, methods and instructions had tests exercising them, and what ones did not? Code Coverage tools are conveniently built-in for Visual Studio 2017 Enterprise Edition, but not for our Professional Edition installations. Much less for any Commun

Scala Collections: A Group of groupBy() Examples

Scala provides a rich Collections API. Let's look at the useful groupBy() function. What does groupBy() do? It takes a collection, assesses each item in that collection against a discriminator function, and returns a Map data structure. Each key in the returned map is a distinct result of the discriminator function, and the key's corresponding value is another collection which contains all elements of the original one that evaluate the same way against the discriminator function. So, for example, here is a collection of Strings: val sports = Seq ("baseball", "ice hockey", "football", "basketball", "110m hurdles", "field hockey") Running it through the Scala interpreter produces this output showing our value's definition: sports: Seq[String] = List(baseball, ice hockey, football, basketball, 110m hurdles, field hockey) We can group those sports names by, say, their first letter. To do so, we need a disc