Java Reference
In-Depth Information
16.3.1
Mock objects
Now that we have our services written, let's examine them. The calculator service
exposes an
API
used by the
CalculatorClient
service to compute some sums or mul-
tiplications. The
CalculatorClient
service, on the other hand, reads some data input
from the command line. This means that if we write a test for this service and invoke
it, we have to enter some data on the command line, and because there's no restric-
tion on the data that we can enter, there's no way to specify our assertions. There's
also no way to automate those tests, because we always have to have someone entering
data on the command line when the tests are executed. The solution for this problem
is simple: refactoring.
We need to refactor the
ClientBundleActivator
in such a way that it allows it to
be easily testable. Listing 16.7 shows the refactored class, where the changed lines are
marked in bold.
Listing 16.7
Refactored
ClientBundleActivator
to enable testability
[...]
public class
ClientBundleActivator implements BundleActivator {
private
String operation = null;
private
String userNumberInput = null;
private double
result = 0;
public void
start(BundleContext context)
throws
Exception {
if
(operation==null || userNumberInput==null) {
initUserInput();
}
ServiceReference reference = context.getServiceReference(
CalculatorService.
class
.getName());
if
(reference !=
null
) {
B
C
D
CalculatorService calculator = (CalculatorService)
context.getService(reference);
double
[] numbers = calculator.parseUserInput(
getUserNumberInput());
if
(getOperation().equals("add")) {
result = calculator.add(numbers);
}
else if
(getOperation().equals("multiply")) {
result = calculator.multiply(numbers);
}
else
{
throw new
UnsupportedOperationException(
"Unknown command: " + getOperation());
}
calculator.printResult(result);
context.ungetService(reference);
}
else
{
System.out.println("Calculator service
is not installed or not started ...");
}
}
E
F