Java Reference
In-Depth Information
You'll use EasyMock ( http://easymock.org/ ) in this example, but any mocking library
will do. You can find the initial setup under chapter07/mocking-example in
the topic's companion code. It contains the log client code from listing 7.1 and a skel-
eton test class that you'll expand on in this section: mock_test/src/org/foo/mock/
LogClientTests.java. You can also find a completed version of the unit test in the solu-
tion directory if you don't feel like typing all this code. Let's go through each of the
five steps in detail and mock out the OSG i API :
Create prototype objects for parts of the API that you want to mock out:
BundleContext , ServiceReference , and LogService . You can do this by adding
the following lines to the empty test case:
1
BundleContext context = createStrictMock(BundleContext.class);
ServiceReference serviceRef = createMock(ServiceReference.class);
LogService logService = createMock(LogService.class);
You use a strict mock for the context, because you want to check the call
sequence.
Script the expected behavior of the log client as it finds and calls the Log-
Service :
2
expect(context.getServiceReference(LogService.class.getName()))
.andReturn(serviceRef);
expect(context.getService(serviceRef))
.andReturn(logService);
logService.log(
and(geq(LogService.LOG_ERROR), leq(LogService.LOG_DEBUG)),
isA(String.class));
Using your knowledge of the service API from chapter 4, you expect that the cli-
ent will call your mock context to find a reference to the LogService , to which
you respond by returning a mock service reference. You expect the client to
pass this reference back your mock context in order to get your mock Log-
Service . Finally, you expect the client to call your mock LogService with a
valid log level and some sort of message string.
Replay the expected behavior to initialize your mock objects:
3
replay(context, serviceRef, logService);
Use your mock objects, and pretend to be the OSG i container:
4
BundleActivator logClientActivator = new Activator();
logClientActivator.start(context);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
logClientActivator.stop(context);
Consider the active lifecycle of an OSG i bundle: first it's started, and some time
later it's stopped. You don't worry about mimicking the resolution stage in this
 
Search WWH ::




Custom Search