What Should you Unit Test? – Testing Techniques 3

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 to the Name class:

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;
  }

…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 Address 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 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.

Reference: What Should you Unit Test? – Testing Techniques 3 from our JCG partner at the Captain Debug blog

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


7 + three =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close