Java Reference
In-Depth Information
Chapter 7 introduced mock objects, and we saw mock objects frameworks that can
produce fake instances of interfaces that we can use in tests. That's exactly what we're
going to do in listing 16.8.
Listing 16.8
Mock test for the
CalculatorService
[...]
public class
TestClientCalculatorServiceMock {
B
C
private
Mockery context =
new
JUnit4Mockery();
private
BundleContext mockBundleContext;
D
private
ServiceReference mockServiceReference;
@Before
public void
setUp() {
mockBundleContext = context.mock( BundleContext.class );
mockServiceReference = context.mock( ServiceReference.class );
final CalculatorImpl service =
new
CalculatorImpl();
E
context.checking(
new
Expectations()
{
{
oneOf(mockBundleContext).getServiceReference(
CalculatorService.
class
.getName());
will(returnValue(mockServiceReference));
oneOf(mockBundleContext).getService(mockServiceReference);
will(returnValue(service));
oneOf(mockBundleContext).ungetService(mockServiceReference);
}
} );
}
F
G
@Test
public void
testAddMethod()
throws
Exception {
ClientBundleActivator activator =
new
ClientBundleActivator();
activator.setOperation( "add" );
activator.setUserNumberInput( "1 2 3 4 5 6 7 8 9" );
activator.start( mockBundleContext );
assertEquals( "The result is not the same as expected",
activator.getResult(), 45, 0 );
}
H
I
J
@Test
public void
testMultiplyMethod()
throws
Exception {
ClientBundleActivator activator =
new
ClientBundleActivator();
activator.setOperation( "multiply" );
1)
activator.setUserNumberInput( "1 2 3 4 5 6 7 8 9" );
activator.start( mockBundleContext );
assertEquals( "The result is not the same as expected",
activator.getResult(), 362880, 0 );
}
}