Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

An Introduction to TDD With Java

DZone's Guide to

An Introduction to TDD With Java

Learn the basics of Test-Driven-Development (TDD) with Java and JUnit, but the concepts are applicable to any language.

· DevOps Zone
Free Resource

Download the blueprint that can take a company of any maturity level all the way up to enterprise-scale continuous delivery using a combination of Automic Release Automation, Automic’s 20+ years of business automation experience, and the proven tools and practices the company is already leveraging.

Welcome to an introduction to Test Driven Development (TDD) series. We will talk about Java and JUnit in the context of TDD, but these are just tools. The main aim of the article is to give you a comprehensive understanding of TDD regardless of the programming language and testing framework.

In my opinion, if you don’t use TDD in your project you are either lazy or you simply don’t know how TDD works. Excuses about lack of time don’t apply here.

About This Post

In this post I’ll explain what TDD is and how it can be used in Java, unit testing in TDD what you have to cover with your unit tests, and which principles you need to adhere in order to write good and effective unit tests.

If you have already know everything about TDD in Java, but you are interested in examples and tutorials, I recommend you to skip this part and continue to the next one (it will be published in one week).

What is TDD?

If somebody asks me to explain TDD in few words, I say TDD is a development of tests before a feature implementation. You can argue that it’s hard to test things which are not existing yet. And Kent Beck will probably give you a slap for this.

So how is it possible? It can be described by following steps:

  1. You read and understand requirements for a particular feature.

  2. You develop a set of tests which check the feature. All of the tests are red, due to absence of the feature implementation.

  3. You develop the feature until all tests become green.

  4. Refactor the code.

TDD flow

TDD requires a different way of thinking, so in order to start TDD you need to forget the way you developed code before. This process is very hard. And it is even harder if you don’t know how to write unit tests. But it’s worth it.

Developing with TDD has valuable advantages:

  1. You have a better understanding of a feature you implement.

  2. You have robust indicators of feature completeness.

  3. Code is covered with tests and has less chance to be corrupted by fixes or new features.

The cost of these advantages is pretty high – inconvenience related to switching to a new development manner and time which you spend for developing each new feature. It’s a price of quality.

So that’s how TDD works – write red unit tests, start implementing a feature, make the tests green, and refactor the code.

Place of Unit Tests in TDD

Since unit tests are the smallest elements in the test automation pyramid, TDD is based on them. With the help of unit tests we can check the business logic of any class. Writing unit tests is easy if you know how to do this. So what do you test with unit tests, and how do you do it?  I’ll try to illustrate answers in a concise form.

place of unit test in testing pyramid

A unit test should be as small as possible. Don’t think about this as one test for one method. That is possible, but as a rule one unit test implies invocation of several methods. This is called testing of behavior.

Let’s consider the Account class:

public class Account {

    private String id = RandomStringUtils.randomAlphanumeric(6);
    private boolean status;
    private String zone;
    private BigDecimal amount;

    public Account() {
        status = true;
        zone = Zone.ZONE_1.name();
        amount = createBigDecimal(0.00);
    }

    public Account(boolean status, Zone zone, double amount) {
        this.status = status;
        this.zone = zone.name();
        this.amount = createBigDecimal(amount);
    }

    public enum Zone {
        ZONE_1, ZONE_2, ZONE_3
    }

    public static BigDecimal createBigDecimal(double total) {
        return new BigDecimal(total).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("id: ").append(getId())
                .append("\nstatus: ")
                .append(getStatus())
                .append("\nzone: ")
                .append(getZone())
                .append("\namount: ")
                .append(getAmount());
        return sb.toString();
    }

    public String getId() {
        return id;
    }

    public boolean getStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String getZone() {
        return zone;
    }

    public void setZone(String zone) {
        this.zone = zone;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        if (amount.signum() < 0)
            throw new IllegalArgumentException("The amount does not accept negative values");
        this.amount = amount;
    }
}

There are 4 getter methods in the class. Pay extra attention to them. If we create a separate unit test for each getter method, we get too many redundant lines of code. This situation can be handled with help of behavior testing. Imagine that we need to test the correctness of the object using one of its constructors. How do we check that the object is created as expected? We need to check a value of each field, hence getters can be used in this scenario.

Create small and fast unit tests, because they should be executed before each commit to a Git repository and new build to a server. Consider an example with real numbers in order to understand importance of unit tests speed.

Let’s assume a project has 1000 unit tests. Each of them takes 100ms. As a result all tests take 1 minute and 40 seconds. Actually 100ms is too long for a unit test, so you have to reduce runtime by applying different rules and techniques, e.g. do not perform database connection in unit tests (by definition unit tests are isolated) or perform initialisations of expensive objects in the @Before block.

Choose good names for unit tests. A name of a test can be as long as you want, but it should represent what the test verifies. For example if I need to test a default constructor of the Account class, I’ll name it defaultConstructorTest. One more useful piece of advice for choosing a test’s name is to write the test logic before you name the test. While you are developing a test you learn what happens inside of it, making it easier to name.

Unit tests should be predictable. This is the most obvious requirement. I’ll explain it by example. In order to check the operation of a money transfer (with 5% fee) you have to know which amount you sent and how much you get as output. This test scenario can be implemented as sending of $100 and receiving of $95.

And finally unit tests should be well-grained. When you put one logical scenario per test you can achieve informative feedback. And in cases of a single failure, you will not lose information about the rest of the functionality.

unit tests principles

All these recommendations are aimed to improve the unit test's design. But there is one more thing you need to know – basics of test design techniques.

Basics of Test Design Techniques

Writing tests is impossible without  test data. When you are testing a money transfer system you set some amount in the send money field. The amount is our test data in this case. So which values should you choose for testing? In order to answer this question we need to go through the most popular test design techniques. The general purpose of test design technique is simplifying the composing of test data.

First let’s pretend that we can send just positive integer amounts of money, and we cannot send more than 1000. That’s can be presented as:

0 < amount <= 1000; amount in integer

All our test scenarios can be split into two groups: positive & negative scenarios. The first one is for test data which is allowed by a system and leads to successful results. The second one is for so called “failure scenarios”, when we use inappropriate data for interaction with the system.

According to the classes of equivalence technique we can select single random integer numbers from the range (0; 1000]. Let it be 500. Since the system works for 500 it should work fine for all integer numbers from the range. So 500 is a valid value. We can also select invalid input from the range. It can be any number with a floating point, for instance 125.50

Then we have to refer to the boundary testing technique. We have to choose two valid values from the left and right sides of the range. In our case we take 1 as the lowest allowed positive integer and 1000 from the right side.

The next step is to choose two invalid values on boundaries. So it’s 0 and 1001.

So in the end we have 6 values which we need to use in the unit test:
(1, 500, 1000) – for positive scenarios
(0, 125.50, 1001) – for negative scenarios

Summary

In this post I tried to explain all aspects of TDD and show how important unit tests are in the TDD. So I hope after the details and theory we can continue in practice. In my next article I’ll demonstrate how to develop tests before functionality. We will do it step by step, starting from documentation analysis and finishing with code refactoring.

Be sure that all tests will be green =)

Download the ‘Practical Blueprint to Continuous Delivery’ to learn how Automic Release Automation can help you begin or continue your company’s digital transformation.

Topics:
test driven developement ,java

Published at DZone with permission of Alexey Zvolinskiy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}