Test Data Setup: Staying clean, DRY, and sane

by Seth Petry-Johnson 24. July 2012 18:27

There are many good reasons to avoid hitting a database in your tests. I agree with all of them, and I try my best to avoid doing it.

However, some tests do need to hit the database. Even the most dependency-injected and mock-infested system should hit the database when testing the data access layer... after all, what good is a test suite that doesn't test any of your actual data access logic? And if you're smart and follow the testing pyramid then you'll have some integration and acceptance tests that need a database as well.

In "Rules for Effective Data Tests" I mentioned some strategies for setting up those data tests. This post expands on those ideas and shows how to keep your setup code clean, DRY and maintainable.

What's so difficult about setting up a data test?

First, a definition. When I say "data setup" I'm talking about anything you do in the body of a test [or a setup method] to create the database records needed for a given test to execute.

While similar to the setup of a "true" unit test, interacting with a Real Life Database™ makes things a little more interesting. Some of the challenges we have to overcome are:

  • Test residue: Unless we delete it, data created by each test remains in the database when the test exits. At best this just wastes space; at worst, it starts to interfere with other tests. (See here for a common solution to this problem) 
  • Database constraints: Foreign key constraints are a real pain. When setting up test data you need to create the entire data graph to satisfy the database constraints, regardless of if those relationships are actually relevant to the test.  
  • Verbosity: Because of the foreign key issues mentioned above, setting up data tests requires more code than setting up a unit test. This makes tests harder to write, harder to maintain, and harder to keep DRY. 
  • False negatives: The more complex the setup, the greater the change that tests will fail not because your application logic is wrong, but because you screwed up the setup. 
  • Painful to debug: Debugging a data test is more difficult and time consuming than a unit test. Not only does the test take longer to run, but debugging it often means poking around in both the application debugger and a database tool.
A daunting list to be sure, but it's manageable.

Characteristics of good setup code

The primary contributor to the quality and maintainability of your data tests is the setup code; the easier it is for someone to understand the specific scenario you are creating, the better equipped they are to maintain that test.

Conversely, the harder the scenario is to understand and maintain, the less value that test will provide over time. Tests that contain an unintelligible jumble of setup code have a very real risk of being deleted (rather than fixed) if they ever break due to new code changes.

So what is "good" setup code? It should be: 

  • Highly expressive (high signal-to-noise ratio). Readers should be able to very quickly understand the scenario(s) you are creating without mentally parsing code. 
  • Highly reusable through the use of default values. If I just need to create a Person, let me call "CreatePerson()" and fill in the details for me. 
  • Easily customizable to each test's needs. Since the customized data are usually very relevant to the test at hand, it should be easy for a reader to spot them.  
  • Maintainable; databases change, and its not uncommon to add a new required field. The fewer changes you need to make to existing test code to support these changes the better.
These characteristics aren't specific to data tests, of course. They apply equally well to setup code of any kind.
 
So what happens when we apply these principles? Read on for specific suggestions...

Data Helpers: the Object Mother pattern for DB entities

The Object Mother pattern describes a special kind of factory class that encapsulates the instantiation of an object (or group of objects) in a specific state, usually mirroring a common scenario in the underlying domain. For instance, you might have an Object Mother that creates an Order object, adds some Order Items and marks it as Shipped. The goal is to turn a complex initialization process into a one-liner so that it is easier to read and maintain.

We can use this same approach in a data test, except that instead of constructing an object in code we need to create one or more records in the database. I call these classes "Data Helpers" and they generally:
  • Are static classes: These classes have no need to ever be mocked out, and making them static makes them easier to invoke in your tests. Omitting the need to instantiate them increases the signal-to-noise ratio and keeps setup code lean.
  • Follow a naming convention: It's important that other developers can discover and use your helpers, so follow an obvious naming convention. I recommend:
    • Put all Data Helpers in the same namespace
    • Name according to the primary entity being created. OrderHelper, CustomerHelper, etc.
  • Create a single "primary" entity: I find that Data Helpers are best focused around a single primary entity, such as an Order. It's fine if they create child or related data for the primary entity, but they should avoid creating a large number of collaborating entities. See below for how to use "scenario" objects for more complicated setups.
  • Treat performance as an important, but secondary, concern: Data Helpers provide their primary value by reducing the cost to create and maintain data tests, so whenever "speed of execution" and "ease of use" are at odds with each other, favor ease of use. That doesn't mean you shouldn't care about performance, and in fact you should care very much. Just not so much that you erode the overarching goal. You can easily offload the performance hit to the CI server.  (You do have a CI server, right?)
The methods exposed by a Data Helper class should:
  • Use optional parameters for as much as possible: A primary benefit of Data Helpers is dramatically increasing the signal to noise ratio within setup logic. Callers should only have to specify the specific values that are significant to their test; all other properties should be created using reasonable defaults.
  • Are semantic: Don't be afraid to create highly specialized methods, such as CreateOrderWithBackorderedItems(), which usually just delegate to a more general method with a specific combination of arguments. This can dramatically improve maintainability; if you add a new field to the database, and you can easily infer the correct default value based on the semantics of the method call, then you can implement that new field in the helper method without touching any of the existing tests.
  • Return the created entity: The caller probably needs to know about the data that was created, so return the entity object that you just created. 

Data Scenarios: a bunch of Object Mothers working together

Data Helpers are great when you need to create test data, especially if you want to specify a few key properties and use defaults for the rest.

But what if you want to create multiple related entities, or you want to reuse a specific setup in multiple tests? For instance, you need to create a Customer, with completed Orders in the past, and an in progress Order that's ready for checkout. In these cases, I create a special type of Data Helper that I call a "Data Scenario". 

Scenario objects have these characteristics:

  • Create a large or complex set of data: Just like Data Helpers reduce individual object setup to a one-liner, Scenarios reduce multiple object setup to a one-liner.
  • Model real-world scenarios: The whole point of a Scenario is to encapsulate realistic data patterns that might exist in production.
  • Expose a smaller set of configurable defaults: Scenarios tend to expose fewer arguments than Data Helpers because they are better suited to creating general purpose groups of data rather than highly-specific records.
  • Are often used in fixture-level setup: A common pattern is for a group of tests to share a Scenario object that is created in the test fixture's setup routine, and then provide test-specific adjustments to the Scenario via inline Data Helper calls. 
  • Are instantiated, not static: Scenario objects are NOT static methods of a helper class. Instead, they are objects that get instantiated and perform their data manipulations in the constructor. This allows Scenarios to be created, manipulated and passed around as needed.
  • Expose pointers to the interesting data: A Scenario object should contain public properties containing references to the entities it creates (or at least their IDs). This allows test code to further manipulate the Scenario data or to make assertions against it. 

Common objections to these techniques

Some of the specific objections that I've heard are:

  • It takes a lot of time/code to write/maintain helpers: Yes, on a complex system you'll end up with a decent amount of non-production code implementing these helpers. And yes, it requires an investment of time to get started. But I've been using these patterns for two years on a large application and I'm absolutely convinced the effort is justified. Once you get a decent library of helpers set up it becomes really, really easy to write tests... sometimes even easier than setting up expectations in a true unit test!
  • The tests take a long time to run: Yes, they do. You should do your best to avoid hitting the database except when necessary, and you should lean on your CI server to run the whole suite for you. If you can find a way to test the data access code without hitting the database, I'll eat my hat.
  • Its hard to know what helpers exist: True, if you're not the author of the helpers then they are harder to use. That's why it's so important to follow good naming conventions. You can also, you know, talk to your teammates if you create a new helper or wonder if one exists.
  • I don't wanna: If you don't care about testing the data access code, or you don't care about writing good tests, then I got nothin'. Go play in traffic.
Let's face it: data tests suck, but they are a necessary evil. The goal is to maximize their value while minimizing their cost, and that's what these techniques do.

Closing thoughts

In my experience it works best to think of Scenarios as the broad context in which a test will execute; they create all of the background data that is necessary for a test to run, but isn't very significant by itself. Data Helpers are used to create specific data records that are significant to a specific test. Used together, they create a very rich language for setting up your test data in an easy to write, easy to read, and easy to maintain form.

I've been using these techniques on a multi-year, multi-developer, multi-hundreds-of-thousands-LOC project and I am convinced that they are directly responsible for allowing us to maintain high test coverage on a very data-intensive app. 

Happy testing!  

Defensive Programming: Avoid Tomorrow's Debugging, Today

by Seth Petry-Johnson 18. July 2012 04:38

Just as I was trying to write a good intro to this post, Jimmy Bogard tweeted:

I've felt that frustration myself many times. I work on large software systems and often have to troubleshoot hard-to-replicate, data-specific defects given only an error message and limited access to the production environment. Turning this limited data into an actionable bug report can be very, very difficult.

This experience has shown me that there are two types of programmers: those that intentionally craft code that it is easy to debug, and those that don't. Programmers that don't do this are, unfortunately, incredibly common and incredibly costly to an organization. Don't be that guy/gal whose code everyone hates to debug!

This post explains some coding techniques that will make your systems easier to troubleshoot and less costly to maintain. Use them; your team will love you for it!

What does "defensive programming" look like?

"Defensive Programming" refers to a collection of coding techniques that decrease maintenance costs by surfacing defects as early as possible, and by making them easy to troubleshoot. There are many articles on this topic, some arguing for and against it, and I encourage you to read them for additional insight.

Specifically, defensive programming means that you:

Write clean, simple, intent-revealing code

This is a universal requirement, I don't care if you're coding defensively, offensively or somewhere in the middle. The easiest defect to fix is the one that never occurs, and simple code is less likely to contain defects than complex code, so keep your designs as simple as possible.

(If you don't agree with this statement, stop reading and go play in traffic... your team will thank you!)

Assume inputs are tainted until proven otherwise

Most applications need data to function and many programmers make assumptions about their data, such as "this string will never be empty" or "this value will always be positive". 

Unfortunately, that string can be empty in some cases, and that value will be zero at some point in time. If you don't validate your assumptions before using the data then you risk intermittent, hard-to-troubleshoot errors. 

Therefore, do sanity checks on your input BEFORE you use it. Use a "design by contract" tool like Code Contracts for .NET if you can, or do it manually if you must. In any case, validate your input before you use it and display a helpful error message if validation fails. (See below for more on helpful exceptions)

In addition to making these errors easier to diagnose, treating all input as potentially hostile is also a security best practice. Sanity check your data and make both your teammates AND your security team a little happier!

Fail early, with useful messages

This is as important as it gets.

Imagine you get an error report that says "Sequence contains no elements". What do you do next? If you're lucky enough to get a stack trace then you can trudge through the code looking for the offending line, but what happens if the offending line contains multiple statements chained together? 

Now imagine the error report says "Could not obtain order items for order 1234; sequence contains no elements". You haven't looked at a single line of code yet, and you already have way more information about the problem!

Same goes for null reference exceptions: Would you rather see "Object reference not set to an instance of an object" or "Cannot calculate sales tax for order 1234; Tax Calculator object was null"?  

The key principle here is that you should anticipate errors that might occur and throw exceptions that provide key debugging info directly in the error message:

  • Help the programmer locate the statement that failed and understand WHY it failed.
  • Include key pieces of data needed to reproduce it: order ID, customer ID, etc. (Obviously, be careful not to expose identifiers that could compromise the security of your system!)
Ask yourself, "if this occurs in production 6 months from now, what pointers would I need to zero in on the problem?" and then include those pointers in the exception. 

Use "fail safe" default values, where appropriate

In many cases, invalid data may not necessarily require an exception. For example, ask yourself these questions about each variable or statement you write:

  • Can I treat null strings the same as empty strings?
  • Can I treat null sequences (lists, arrays, etc) the same as empty sequences?
  • If a string parsing fails, can I substitute a default value instead of throwing an exception?
If the answer to any of these questions is "yes" then use the null coalescing operator or conversion helpers to convert null or invalid values into something less "exception prone". I rarely need to differentiate between null and empty sequences so I've written an .ToEmptyIfNull() extension method that I use whenever I need to iterate over a collection. Major reduction in null reference exceptions for negligible effort.
 
Of course, sometimes you DO care about differentiating between null and empty, or ensuring a parse succeeds. In those cases just throw a helpful error message (see above) as soon as you detect the problem. 

"Future proof" your program flow

I've seen a lot of defects occur when business conditions change, and something that "could never happen" when the code was written suddenly becomes possible. 

Examples:

  • When you write a switch statement, always include a default branch. It's better to have the default branch throw an exception like "not implemented condition 'FOO'" than silently fall through and cause a potentially harder-to-debug error.  (Of course, you do your best to avoid switch statements, don't you?)  
  • When you have a chain of if/else-ifs, always include an else branch. If it should never be reached, throw an exception that explains the conditions that occurred and why you expected them to never happen.  
  • If you're dealing with combinations of different states or variables, and certain combinations "should never occur", go ahead and handle those combinations anyway. It's better to throw an exception you can control than to let the system fail on its own.  (For example, "Order 123 has status SHIPPED, but IS_CANCELLED was true; is the update service malfunctioning?")

Go, make the world a brighter place! 

Using these techniques can help you avoid errors in production and can make it easier to resolve errors that do occur.  Using them will bring joy to the hearts of men and will make you beloved amongst your teammates. Use them; do it for the children.

Seth Petry-Johnson

I'm a software architect and consultant for Heuristic Solutions.

I value clean code, malleable designs, short feedback cycles, usable interfaces and balance in all things.

I am a Pisces.

Month List