Heart containing Coding Chica Java 101

A New Instance Every Test! JUnit Classes And Fields

TIP: References Quick List

Table of Contents

  1. Table of Contents
  2. Introduction
  3. Unit Test Updates
  4. Build Success
  5. Commit

Introduction

You may have noticed that most of our unit tests in the src/test/java/codingchica.java101.model/AnimalTest.java class contain the setup step of Animal animal = new Animal();

Unit Test Updates

Let’s update src/test/java/codingchica.java101.model/AnimalTest.java to have a new field:

/**
 * An instance of the object under test.
 */
private Animal animal = new Animal();

Then, we can delete this now-duplicated step in each of our tests. In this case, with the instance declaration and Javadoc, it only saves us six lines. However, that savings will increase as the test class’s method count increases.

The draw back is that some of the test setup now exists outside of the test method. Readers reviewing this code will need to jump to the field declaration to see how the animal variable is initialized.

Build Success

If we run the Maven build now, it should show success.

Commit

Let’s commit in small increments. Now is a good time.

A New Instance Every Test! JUnit Classes And Fields

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.