Java Reference
In-Depth Information
pendencies the
DiscountManagerBean
uses with the assumption that those dependen-
cies will work properly. But how do you know if they'll work properly?
The answer is more unit tests! Just as this example is a unit test for
DiscountManager-
Bean
, you'll also want to create a unit test for
MembershipLevelBean
. A good rule to
follow is if you mock one of your application's classes for a unit test, then whatever class
you mocked should have its own unit test too.
Next is one of the
@Test
methods, specifically the
userGetsGoldDiscount()
unit
test method . The name of the test method should indicate the goal of the test, and
by this method's name it's clear it's going to test that the
DiscountManagerBean
re-
turns the appropriate discount if the member has a gold membership level. Inside this unit
test method, the membership level is set to
GOLD
. The
DiscountManagerBean
.findDiscount()
method is called and the results are checked against what was ex-
pected for this test to pass . Because unit tests for the other membership levels are al-
most identical to
userGetsGoldDiscount()
, we won't look at them in more detail.
You may download the code for this chapter to see them. But we'll look at one additional
unit test, the
userGetsNoDiscountBecauseNotAMember()
method.
By the name of the method, you can determine that this unit test needs to verify that
Dis-
countManagerBean
behaves properly if there's no membership level. To handle this
test case, you use
Mockito.when()
inside the unit test method to define a new re-
sponse for the mocked
MembershipLevelManager
class. The new response is to re-
turn
null
. By having the mocked
MembershipLevelManager
class return
null
,
you can then verify that
DiscountManagerBean
is still working properly in this case.
Unit testing is very powerful. It provides some indication as to whether your application
is going to work correctly, but it's not foolproof. Once real objects are created by the Java
EE server and wired together, a lot can change that can't be accounted for in unit testing.
This is especially the case when your application depends on an external resource such as a
database. The
DiscountManagerBean
depends on a database to hold the membership-
level data, but testing whether data can be successfully retrieved from a database is outside
the responsibilities for a unit test. To ensure your entity classes are working with the data-