Enterprise Java

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 :

Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button