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); ...

Get Quality Code: Software Testing Principles, Practices, and Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.