Java Reference
In-Depth Information
G
public void
initUserInput() {
BufferedReader in = null;
try
{
in =
new
BufferedReader(
new
InputStreamReader(System.in));
System.out.println("Enter operation (add or multiply):");
operation = in.readLine();
H
I
System.out.println("Enter several
numbers separated with a space:");
userNumberInput = in.readLine();
}
catch
(IOException ex) {
System.err.println("Error reading from the reader.");
ex.printStackTrace();
}
finally
{
try
{
in.close();
}
catch
(IOException e) {
System.err.println("Error closing the reader.");
e.printStackTrace();
}
}
}
// Getters and setters...
}
We start by extracting all the data the user normally enters on the command line (the
operation
and the
numbers
separated by spaces) as instance variables to the class
B
.
We extract the
result
from the computation as a local variable
C
, and we provide
getters and setters for both
B
and
C
. This gives us the opportunity to set those
parameters before we start the
ClientBundleActivator
as well as to assert the
expected
result
. Next, in the
start
method we add a check to see if the user data has
been set up
D
, and in case it hasn't we call the
initUserInput
method
G
. As you can
see in
E
, everywhere in our code that we want to use the user data, we use the getter
methods of the class. At this point we're sure that this data will be set up, either by the
setter methods or by the
initUserInput
method, which reads the data from the com-
mand line. In
F
we check the command we want to issue and call the corresponding
method in the CalculatorService accordingly. Notice that the result is this time kept in
a local variable, to which we have access through the getter methods.
The
initUserInput
method
G
is called when we have no user data defined
through the setter methods. This method has the responsibility for reading the oper-
ation we want to issue
H
as well as the numbers on which we want to issue the com-
mand
I
.
Now that we've refactored the
ClientBundleActivator
class, we can test it. The
class contains one entry-point method called
start
, which we want to unit test. In
order to do this we must obtain a valid
BundleContext
object, because the method
defines it as a parameter.
BundleContext
itself is an interface, so we have no way
to instantiate.