Java Reference
In-Depth Information
should reduce dependencies as much as possible. If your classes depend on many
other classes that need to be instantiated and set up with some state, then your tests
will be complicated—you may need to use some complicated mock-objects solution
(see chapter 6 for mock objects).
A solution to reducing dependencies is to separate your code between methods
that instantiate new objects (factories) and methods that provide your application
logic. Consider listing 5.1.
Listing 5.1
Reduce dependencies
class Vehicle {
Driver d = new Driver();
boolean hasDriver = true;
private void setHasDriver( boolean hasDriver) {
this.hasDriver = hasDriver;
}
}
Every time we instantiate the Vehicle object, we also instantiate the Driver object.
We've mixed the concepts. The solution would be to have the Driver interface passed
to the Vehicle class, as in listing 5.2.
Listing 5.2
Pass the Driver to the Vehicle
class Vehicle {
Driver d;
boolean hasDriver = true ;
Vehicle(Driver d) {
this .d = d;
}
private void setHasDriver( boolean hasDriver) {
this.hasDriver = hasDriver;
}
}
This allows us to produce a mock Driver object (see chapter 6) and pass it to the Vehicle
class on instantiation. Furthermore, we can mock any other type of Driver implemen-
tation— JuniorDriver , SeniorDriver , and so on—and pass it to the Vehicle class.
5.2.3
Create simple constructors
By striving for better test coverage, we add more and more test cases. In each of these
test cases, we do the following:
Instantiate the class to test
Set the class into a particular state
Assert the final state of the class
 
 
 
 
 
Search WWH ::




Custom Search