Java Reference
In-Depth Information
Listing 5.7 illustrates how unit tests can help design the implementation. The get-
BalanceOk method shows that the getBalance method of Account returns the account
balance as a long and that this balance can be set in the Account constructor. At this
point, the implementation of Account is purely hypothetical, but writing the unit tests
allows you to focus on the design of the code. As soon as you implement the class, you
can run the test to prove that the implementation works. If the test fails, then you can
continue working on the implementation until it passes the test. When the test passes,
you know that your code fulfills the contract.
Listing 5.7
Unit tests as a design guide
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestAccount {
@Test
public void getBalanceOk () {
long balance = 1000;
Account account = new Account(balance);
long result = account.getBalance();
assertEquals(balance, result);
}
}
When you use the test as the method's first client, it becomes easier to focus purely on
the API . Writing the tests first provides the following:
Means to design the code
Documentation as to how the code works
Unit tests for the code
Someone new to the project can understand the system by studying the functional test
suite (high-level UML diagrams also help). To analyze a specific portion of the applica-
tion in detail, they can drill down into individual unit tests.
5.3.2
The TDD two-step
Earlier, we said that TDD tweaks the development cycle to go something like test,
code, (repeat), and ship. The problem with this chant is that it leaves out a key step.
It should go more like this: test, code, refactor , (repeat), and ship. The core tenets of
TDD are to
Write a failing automatic test before writing new code
1
Eliminate duplication
2
Eliminating duplication ensures that you write code that's not only testable but also
maintainable . When you eliminate duplication, you tend to increase cohesion and
decrease dependency. These are hallmarks of code that's easier to maintain over time.
Other coding practices have encouraged us to write maintainable code by anticipat-
ing change. In contrast, TDD encourages us to write maintainable code by eliminating
 
 
 
 
 
 
 
Search WWH ::




Custom Search