DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • WireMock: The Ridiculously Easy Way (For Spring Microservices)
  • DevOps Pipeline and Its Essential Tools
  • Testing, Monitoring, and Data Observability: What’s the Difference?
  • How To Backup and Restore a PostgreSQL Database
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Single-Statement Unit Tests

Single-Statement Unit Tests

The biggest benefit of this principle is that tests become declarative and object-oriented instead of being algorithmic, imperative, and procedural.

Yegor Bugayenko user avatar by
Yegor Bugayenko
·
May. 24, 17 · Opinion
Like (4)
Save
Tweet
Share
7.08K Views

Join the DZone community and get the full member experience.

Join For Free

Many articles and books have already been written about unit testing patterns and anti-patterns. I want to add one more recommendation which, I believe, can help us make our tests, and our production code, more object-oriented. Here it is: a test method must contain nothing but a single assert.

Look at this test method from RandomStreamTest from OpenJDK 8, created by Brian Goetz:

@Test
public void testIntStream() {
  final long seed = System.currentTimeMillis();
  final Random r1 = new Random(seed);
  final int[] a = new int[SIZE];
  for (int i=0; i < SIZE; i++) {
    a[i] = r1.nextInt();
  }
  final Random r2 = new Random(seed);
  final int[] b = r2.ints().limit(SIZE).toArray();
  assertEquals(a, b);
}

There are two parts in this method: the algorithm and the assertion. The algorithm prepares two arrays of integers and the assertion compares them and throws AssertionError if they are not equal.

I'm saying that the first part, the algorithm, is the one we should try to avoid. The only thing we must have is the assertion. Here is how I would re-design this test method:

@Test
public void testIntStream() {
  final long seed = System.currentTimeMillis();
  assertEquals(
    new ArrayFromRandom(
      new Random(seed)
    ).toArray(SIZE),
    new Random(seed).ints().limit(SIZE).toArray()
  );
}
private static class ArrayFromRandom {
  private final Random random;
  ArrayFromRandom(Random r) {
    this.random = r;
  }
  int[] toArray(int s) {
    final int[] a = new int[s];
    for (int i=0; i < s; i++) {
      a[i] = this.random.nextInt();
    }
    return a;
  }
}

If Java had monikers, this code would look even more elegant:

@Test
public void testIntStream() {
  assertEquals(
    new ArrayFromRandom(
      new Random(System.currentTimeMillis() as seed)
    ).toArray(SIZE),
    new Random(seed).ints().limit(SIZE).toArray()
  );
}

As you can see, there is only one "statement" in this method: assertEquals().

Hamcrest with its assertThat() and its collection of basic matchers is a perfect instrument to make our single-statement test methods even more cohesive and readable.

There are a number of practical benefits of this principle if we agree to follow it:

  • Reusability. The classes we will have to create for test assertions will be reusable in other test methods and test cases. Just as, in the example above, ArrayFromRandom could be used somewhere else. Similarly, Hamcrest matchers may and will constitute a library of reusable test components.
  • Brevity. Since it will be rather difficult to create a long test method when it only has a single assert, you and your fellow programmers will inevitably write shorter and more readable code.
  • Readability. With a single assert it will always be obvious what the intent of the test method is. It will start with the intent declaration while all other lower level details will be indented.
  • Immutability. It will be almost impossible to have in the production code if test methods have no place for algorithmic code. You inevitably will create to make them testable with a single assert.

The biggest benefit we get when this principle is applied to our tests is that they become declarative and object-oriented, instead of being algorithmic, imperative, and procedural.

unit test

Published at DZone with permission of Yegor Bugayenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • WireMock: The Ridiculously Easy Way (For Spring Microservices)
  • DevOps Pipeline and Its Essential Tools
  • Testing, Monitoring, and Data Observability: What’s the Difference?
  • How To Backup and Restore a PostgreSQL Database

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: