Bootstrapping Constructors

There is a basic dilemma in testing a well-encapsulated class that is so fundamental it is often overlooked: How do you know you have tested it correctly? You do not have access to the attributes of the class, so how do you verify that the constructor did its work correctly?

Sure, you can start with the most fundamental effect of a constructor and verify that a valid object was constructed. In the process, you also verify that no exceptions were thrown. But how do you verify that the internal state was initialized correctly (Listing 6-1)?

Listing 6-1: Testing object construction and the lack of exceptions

public void testMyObject() {
  MyObject sut = new MyObject();
  assertNotNull(sut);
}

If we didn’t insist on strong encapsulation, we could directly query the attributes. However, we all learned on our first day of Object-Orientation Indoctrination that this is a Bad Thing. We learned that the only allowed way to access our attributes should be with our getter methods.

But wait, should we really use methods that have not been tested to verify the behavior of another method? Do we have any other choices? In short, we may—depending on the language—but none that are good enough to use on such a fundamental and consistent basis (Listing 6-2).

Listing 6-2: Using a getter to verify constructor state

public void testMyObject() {
  MyObject sut = new MyObject();
  assertNotNull(sut);
  assertEquals(expectedValue, sut.getAttribute());
}

Let’s resolve this seemingly circular dependency before we proceed. The key to this apparent dilemma is to realize that in normal cases, it is sufficient for the constructor and the simple setters and getters to behave in a manner that is consistent with expectations. Essentially, we are saying, “If it looks like a class and acts like a class, it is safe to treat it like a class.”

Which cases are not part of the aforementioned “normal cases,” and what should we do if we encounter these deviations? Abnormal cases occur when the constructor initializes hidden state or the getters do more than simply pass the value of an attribute. In the former case, we can use techniques to give our tests privileged access to our classes, described in Chapter 9. In the latter case, I would suggest that the methods should be renamed to reveal their more complex nature and that they should not masquerade as getters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.137.38