Java Reference
In-Depth Information
Instead, your test harness can inject carefully managed dependencies into the code
you're trying to test. You can even inject mock objects instead of real objects, which
would be almost impossible if your intercomponent links were all hard-wired.
To see this in action, look at the DesperateCheeseOffer again. It depends on the
Inventory , which requires container-managed JPA and a functioning database. You
don't want to get a bunch of JPA entities and a database going for a unit test. Instead,
you'll mock up an Inventory object and use the setter methods you created for Blue-
print injection for unit testing instead.
Listing 8.6
Using mocked injection to unit test the desperate cheese offer
public class DesperateCheeseOfferTest {
public void testOfferReturnsCorrectFood() {
Food food = mock(Food.class);
when(food.getName()).thenReturn("Green cheese");
Inventory inventory = mock(Inventory.class);
List<Food> foods = new ArrayList<Food>();
when(inventory.getFoodsWhoseNameContains("cheese", 1))
Use Mockito to
mock out classes
DesperateCheeseOffer offer = new DesperateCheeseOffer();
assertEquals("Green cheese", offer.getOfferFood().getName());
Test that cheese offer
behaves as expected
This sort of testing allows you to verify that if the injected Inventory object behaves as
expected, the DesperateCheeseOffer does the right thing. You could also add more
complex tests that confirmed that the cheese offer tolerated the case when Inventory
had no cheeses in it at all, or the case when there was more than one cheese present
in the inventory.
Although tests running outside an OSG i framework are straightforward and can
spot a range of problems, there are several classes of problems they can't detect. In
particular, unit tests will still continue to run cleanly, even if bundles fail to start or
Blueprint services never get injected. To catch these issues, you'll also want to test the
end-to-end behavior of your application, inside an OSG i framework.
How closely this OSG i framework matches your production environment is a mat-
ter of taste. You may choose to do automated integration testing in a minimal envi-
ronment, and follow it up with a final system test in a mirror of your production
system. Alternatively, you may find you flush more problems out more quickly if you
test in a more fully featured environment. The tools and techniques we'll describe for
testing inside an OSG i environment are broadly suitable for both integration and sys-
tem testing.
Search WWH ::

Custom Search