Java Reference
In-Depth Information
D
@Mock
private
UserDao dao;
@Before
public void
setFixtures() {
facade =
new
UserFacadeImpl();
TestSetup.setup(this);
facade.setUserDao(dao);
}
E
@Test
public void
testGetUserById() {
final int
id = 666;
final
User user = newUserWithTelephones();
context.checking(new Expectations() {{
one(dao).getUserById(id);
will(returnValue(user));
}});
UserDto dto = facade.getUserById(id);
assertUser(dto);
context.assertIsSatisfied();
}
F
G
}
This new example is similar to the previous one; the test setup
E
is even exactly the
same. The only differences are the
dao
reference
D
being marked with a
@Mock
anno-
tation defined in another package
B
, the need for a
Mockery
object
C
, and the way
expectations are set and verified (
F
and
G
respectively).
So, given the mock support offered by these three tools, which one should you use
in your project? If you're looking for transparent EasyMock usage, Unitils is clearly
the best option, because it requires less effort in the test cases (no setup or calls to ver-
ify) and is highly configurable. But if you need to use JMock or prefer a clear separa-
tion between expectations and tested code, then Mycila or
FEST
, respectively, is the
more suitable option.
19.3
DbUnit integration
In chapter 17 we presented an in-house framework that uses Java annotations to
facilitate usage of DbUnit datasets in test cases. Wouldn't it be nice if such a frame-
work was offered out of the box? Well, guess what? Unitils'
dbunit
module pro-
vides exactly that!
Unitils provides four modules related to database testing:
database
,
dbunit
,
hibernate
, and
jpa
. The
database
module is mainly responsible for providing a data-
base connection that will be used by tests and managing transactions, although it
offers other features, such as a database maintainer that can be used to synchronize
the developer's databases. Then the
dbunit
module scans the test class for annota-
tions that define which DbUnit datasets should be used on each test. Finally, the
hibernate
and
jpa
modules can be used to inject the necessary
ORM
classes (such as