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
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. What Should you Unit Test? - Testing Techniques 3

What Should you Unit Test? - Testing Techniques 3

Roger Hughes user avatar by
Roger Hughes
·
Nov. 21, 11 · Interview
Like (0)
Save
Tweet
Share
6.65K Views

Join the DZone community and get the full member experience.

Join For Free

I was in the office yesterday, talking about testing to one of my colleagues who was a little unconvinced by writing unit tests. One of the reasons that he was using was that some tests seem meaningless, which brings me on the the subject of what exactly you unit test, and what you don’t need to bother with.

Consider a simple immutable Name bean below with a constructor and a bunch of getters. In this example I’m going to let the code speak for itself as I hope that it’s obvious that any testing would be pointless.

public class Name {

  private final String firstName;
  private final String middleName;
  private final String surname;

  public Name(String christianName, String middleName, String surname) {
    this.firstName = christianName;
    this.middleName = middleName;
    this.surname = surname;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getMiddleName() {
    return middleName;
  }

  public String getSurname() {
    return surname;
  }
}

 

...and just to underline the point, here is the pointless test code:
public class NameTest {

  private Name instance;

  @Before
  public void setUp() {
    instance = new Name("John", "Stephen", "Smith");
  }

  @Test
  public void testGetFirstName() {
    String result = instance.getFirstName();
    assertEquals("John", result);
  }

  @Test
  public void testGetMiddleName() {
    String result = instance.getMiddleName();
    assertEquals("Stephen", result);
  }

  @Test
  public void testGetSurname() {
    String result = instance.getSurname();
    assertEquals("Smith", result);
  }
}
The reason it’s pointless testing this class is that the code doesn’t contain any logic; however, the moment you add something like this:
  public String getFullName() {

    if (isValidString(firstName) && isValidString(middleName) && isValidString(surname)) {
      return firstName + " " + middleName + " " + surname;
    } else {
      throw new RuntimeException("Invalid Name Values");
    }
  }

  private boolean isValidString(String str) {
    return isNotNull(str) && str.length() > 0;
  }

  private boolean isNotNull(Object obj) {
    return obj != null;
  }
...to your class then the whole situation changes. Adding some logic in the form of an if statement generates a whole bunch of tests:
  @Test
  public void testGetFullName_with_valid_input() {

    instance = new Name("John", "Stephen", "Smith");

    final String expected = "John Stephen Smith";

    String result = instance.getFullName();
    assertEquals(expected, result);
  }

  @Test(expected = RuntimeException.class)
  public void testGetFullName_with_null_firstName() {

    instance = new Name(null, "Stephen", "Smith");
    instance.getFullName();
  }

  @Test(expected = RuntimeException.class)
  public void testGetFullName_with_null_middleName() {

    instance = new Name("John", null, "Smith");
    instance.getFullName();
  }

  @Test(expected = RuntimeException.class)
  public void testGetFullName_with_null_surname() {

    instance = new Name("John", "Stephen", null);
    instance.getFullName();
  }

  @Test(expected = RuntimeException.class)
  public void testGetFullName_with_no_firstName() {

    instance = new Name("", "Stephen", "Smith");
    instance.getFullName();
  }

  @Test(expected = RuntimeException.class)
  public void testGetFullName_with_no_middleName() {

    instance = new Name("John", "", "Smith");
    instance.getFullName();
  }

  @Test(expected = RuntimeException.class)
  public void testGetFullName_with_no_surname() {

    instance = new Name("John", "Stephen", "");
    instance.getFullName();
  }
So, given that I’ve just said that you shouldn't need to test objects that do not contain any logic statements, and in a list of logic statements I’d include if and switch together with all the operators (+-*-), and a whole bundle of things that could change and objects state.

Given this premise, I’d then suggest that it’s pointless writing a unit test for the address data access object (DAO) in the Address1 project I’ve been talking about in my last couple of blogs. The DAO is defined by the AddressDao interface and implemented by the JdbcAddress class:
public class JdbcAddress extends JdbcDaoSupport implements AddressDao {

  /**
   * This is an instance of the query object that'll sort out the results of
   * the SQL and produce whatever values objects are required
   */
  private MyQueryClass query;

  /** This is the SQL with which to run this DAO */
  private static final String sql = "select * from addresses where id = ?";

  /**
   * A class that does the mapping of row data into a value object.
   */
  class MyQueryClass extends MappingSqlQuery<Address> {

    public MyQueryClass(DataSource dataSource, String sql) {
      super(dataSource, sql);
      this.declareParameter(new SqlParameter(Types.INTEGER));
    }

    /**
     * This the implementation of the MappingSqlQuery abstract method. This
     * method creates and returns a instance of our value object associated
     * with the table / select statement.
     *
     * @param rs
     *            This is the current ResultSet
     * @param rowNum
     *            The rowNum
     * @throws SQLException
     *             This is taken care of by the Spring stuff...
     */
    @Override
    protected Address mapRow(ResultSet rs, int rowNum) throws SQLException {

      return new Address(rs.getInt("id"), rs.getString("street"),
          rs.getString("town"), rs.getString("post_code"),
          rs.getString("country"));
    }
  }

  /**
   * Override the JdbcDaoSupport method of this name, calling the super class
   * so that things get set-up correctly and then create the inner query
   * class.
   */
  @Override
  protected void initDao() throws Exception {
    super.initDao();
    query = new MyQueryClass(getDataSource(), sql);
  }

  /**
   * Return an address object based upon it's id
   */
  @Override
  public Address findAddress(int id) {
    return query.findObject(id);
  }

}
In the code above, the only method in the interface is:
  @Override
  public Address findAddress(int id) {
    return query.findObject(id);
  }
...which is really a simple getter method. This seems okay to me as there really should not be any business logic in a DAO, that belongs in the AddressService, which should have a plentiful supply of unit tests.

You may want to make a decision on whether or not you want to write unit tests for the MyQueryClass. To me this is a borderline case, so I look forward to any comments...

I’m guessing that someone will disagree with this approach, say you should test the JdbcAddress object and that’s true, I’d personally write an integration test for it to make sure that the database I’m using is okay, that it understands my the SQL and that the two entities (DAO and database) can talk to each other, but I won’t bother unit testing it.

To conclude, unit tests must be meaningful, and a good a definition of ‘meaningful’ is that object under test must contain some independent logic.


1The source code is available from GitHub at:

git://github.com/roghughe/captaindebug.git

 

From http://www.captaindebug.com/2011/11/what-should-you-unit-test-testing.html

unit test

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java Concurrency: LockSupport
  • A Beginner’s Guide To Styling CSS Forms
  • Demystifying Multi-Cloud Integration
  • OpenVPN With Radius and Multi-Factor Authentication

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
  • +1 (919) 678-0300

Let's be friends: