Java Reference
In-Depth Information
7.2
Mocking OSGi
OSG i is just a load of fancy class loaders! Oh, wait, we didn't mean that sort of mocking.
(Besides, we all know by now that there's a lot more to OSG i than enhanced class load-
ing.) We're talking about using mock objects to test portions of code without requiring
a complete system. A mock object is basically a simulation, not a real implementation.
It provides the same API , but its methods are scripted and usually return expected values
or additional mocked objects. Object mocking is a powerful technique because it lets
you test code right from the start of a project, even before your application is complete.
You can also use it to test situations that are hard to recreate with the real object, such
as external hardware failures.
Figure 7.5 represents the dynamic
log client from chapter 4. Let's take this
example and test it outside OSG i by
mocking the API : verifying calls made
to the API and scripting the desired
responses. We'll show you how easy it is
to script scenarios that may be hard to
reproduce in a real container, look at
mocking in a multithreaded environ-
ment, and wrap things up by reliably
demonstrating
getServiceReference
getService
ungetService
log
log
...
Component
<no calls>
the
race
condition
mentioned in section 4.3.1.
Figure 7.5 Mocking in action
7.2.1
Testing expected behavior
How might you use mocking to test an OSG i application? Let's look at code from ear-
lier in this topic: the LogService lookup example from chapter 4 that contained a
potential race condition. Here's a quick reminder of the problematic code.
Listing 7.1 Broken service lookup containing a race condition
public class Activator implements BundleActivator {
BundleContext m_context;
public void start(BundleContext context) {
m_context = context;
startTestThread();
}
public void stop(BundleContext context) {
stopTestThread();
}
class LogServiceTest implements Runnable {
public void run() {
while (Thread.currentThread() == m_logTestThread) {
ServiceReference logServiceRef =
m_context.getServiceReference(LogService.class.getName());
Gets service
reference
B
 
Search WWH ::




Custom Search