Java Reference
In-Depth Information
test because you want to test service usage, not class loading. You know the cli-
ent will spawn some sort of thread to use the LogService , so you wait one sec-
ond to give that thread time to make the call and pause. (Using sleep here isn't
ideal; later, you'll see how you can replace it with proper handshaking.) Then,
when the one second is up, you stop the client bundle.
The last step is to make sure you saw the expected behavior during the test:
5
verify(context, serviceRef, logService);
This method throws an exception if the observed behavior doesn't match.
At this point, you should have a complete test that compiles and runs successfully:
$ cd chapter07/mocking-example
$ ant test
...
test:
[junit] Running org.foo.mock.LogClientTests
[junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 1.157 sec
Excellent: you've confirmed that your client uses the OSG i API correctly when a Log-
Service is available. But what happens when a LogService isn't available; does it han-
dle that too?
7.2.3
Mocking unexpected situations
As we mentioned back at the start of this section, mocking is a powerful testing tech-
nique because it lets you script situations that are hard to re-create inside a test envi-
ronment. Although it's easy to arrange a test in an OSG i container without a
LogService , it would be difficult to arrange for this service to appear and disappear at
exactly the right time to trigger the race condition you know exists in your client code.
With mocking, it's easy.
First, let's test what happens when no LogService is available by adding the follow-
ing expectation between your last expect and the call to replay :
expect(context.getServiceReference(LogService.class.getName()))
.andReturn(null);
This states that you expect the client to begin another call to look up the LogService ,
but this time you return a null reference to indicate no available service. If you try to
run the test now, it will fail because you don't give the client enough time to make a
second call before stopping the bundle. Your log client pauses five seconds between
each call, so you need to add five seconds to the existing sleep :
try {
Thread.sleep(6000);
} catch (InterruptedException e) {}
The client now gets enough time to begin a second log call, but the test still fails:
Search WWH ::




Custom Search