Java Reference
In-Depth Information
The listing starts by importing the necessary classes
B
. Remember that every external
package you use needs to be declared in the
MANIFEST
.
MF
file of the bundle. Every
JU
nit4
OSG
i test case needs to extend from the
OSGiTestCase
class
C
. The
JU
nit4
OSG
i
framework is a
JU
nit 3.x extension, so you need to follow the
JU
nit 3.x rules for writing
test cases.
We start our first
test
method at
D
and get a
ServiceReference
of the service
we wrote and deployed
E
. We get the
ServiceReference
from the
context
object
that
JU
nit4
OSG
i provides us. The framework gives us the access to the
Bundle-
Context
to check the status of the given service, something that we do in
F
. By
asserting the
ServiceReference
isn't
null
, we make sure that the service is installed
and started correctly.
The following
test
methods test the
service
methods; by having the service refer-
ence we can get hold of the service itself (at
G
) and invoke different methods (at
H
)
to see that it behaves the expected way
I
. We also test the exceptional case to provide
a random string (at
J
), and we catch the
NumberFormatException
that we expect to
be raised .
It's a best practice to separate all your
junit-osgi
tests in a separate bundle, and
that's what we're going to do. Go to the calculator-test folder of the source code of the
book, and use Maven or Ant to package the bundle that contains the test from the pre-
vious listing. After you've done this, copy the resultant
JAR
file and paste it in the
FELIX_HOME
/bundle folder so that it's easy to install. The next step is to install and
start the service in the bundle the way we described at the beginning of the chapter.
Our final step is to call the test inside the container
1)
-> junit [BundleId]
replacing the
BundleId
with the number assigned to your module. If you're using the
source code for the topic and there are no errors, the result should be the same as this:
Executing [Client activator tests]
....1
Time: 0
OK (4 tests)
As we already mentioned, the
junit
command is currently available only for the
Apache Felix implementation of
OSG
i. So how can we run our tests if we use any of
the other implementations of
OSG
i? In that case we have to use the
GUI
runner that
comes with the
JU
nit4
OSG
i project.
To use the
GUI
runner, you need to install and start the org.apache.felix.ipojo.
junit4osgi.swing-gui.jar bundle. After the bundle is started, you'll see a Java pop-up
that lets you select the bundles that contain
JU
nit tests. You can select as many as you
want, and after clicking the Execute button you should see the result: a green bar for
passing tests and a red bar for failing tests (see figure 16.2).
This example of executing unit tests through the
GUI
runner concludes our look
at
JU
nit4
OSG
i and this chapter on
OSG
i.