Java Reference
In-Depth Information
if (logServiceRef != null) {
((LogService)m_context.getService(logServiceRef)).log(
LogService.LOG_INFO, "ping");
} else {
alternativeLog("LogService has gone");
}
Gets
instance
C
pauseTestThread();
}
}
}
// The rest of this class is just support code...
}
Notice how this code interacts with the OSG i container. It receives a context object in
the activator start method, uses this context to get a service reference B , and uses this
reference to get the actual instance C . Each of these objects has a well-defined inter-
face you can mock out, and the example code uses only a few methods from each API .
This is good news because when mocking objects you only need to simulate the meth-
ods that are used, not the complete API .
You already know that this code compiles against the OSG i API , and back in chap-
ter 4 you even tried it on an actual framework. But does it use the service API cor-
rectly? This is the sort of test that's hard to write without mocking. Sure, you can run
tests on the container by invoking your code and checking the results as you did
back in section 7.1, but this doesn't tell you if the code is using the container the
right way. For example, the container won't complain if you forget to unget a ser-
vice after you're done with it, but forgetting to do this skews service accounting and
makes it look like your bundle is still using the service when it isn't. The container
also doesn't know if you use the result of getService() without checking for null .
In this example, you may get a NullPointerException if the service disappears in
the short time between checking the reference and using it. Writing a test that's
guaranteed to expose this race condition on a live framework is hard, but trivial with
mock objects.
How exactly does mocking help? Because mock objects are scripted, you can verify
that the right methods are called in the appropriate order. You can throw exceptions
or return null values at any point in the sequence to see how the client handles it.
Enough talk, let's try mocking ourselves.
7.2.2
Mocking in action
Typically, five steps are involved in mocking out an API :
Mock —Create prototype mock objects
1
Expect —Script the expected behavior
2
Replay —Prepare the mock objects
3
Te s t —Run the code using the mock objects
4
Verify —Check that the behavior matches
5
Search WWH ::




Custom Search