Java Reference
In-Depth Information
The first thing you see in this unit test is that it has a number of class-level properties .
These properties will have similar values for all the unit tests so they're pushed to the class
level to avoid a lot of repeated code.
Next is the annotated
@Before
method responsible for setting these class-level properties
before a test is run.
Member
is created with static data for the test. The same is
also done for
MembershipLevel
.
MembershipLevelManager
gets some spe-
cial treatment because it's mocked using
Mockito.mock()
. Mocking allows you
to easily define how the object is to behave during the unit test. The
Mockito.when()
method is used to set behavior for the unit test so that when
findByMemberId()
is called with
member.getId()
as the method parameter, the mocked
Member-
shipLevelManager
object will return the
MembershipLevel
object instance. Once
the mock is created, you can create an instance of
DiscountManagerBean
, which
is the class you want to unit test.
Test only one class at a time
You may be wondering how you'll know if
MembershipLevelManager
is working
when you mock it. After all, if you mock
MembershipLevelManager
, you're not ex-
ecuting its code.
Remember, this is okay because the focus of this unit test is on the
DiscountManager-
Bean
. The unit test should focus only on
DiscountManagerBean
and mock any de-