Java Reference
In-Depth Information
As shown in these examples, Unitils DbUnit support is similar to the framework
developed in chapter 17, although each has its pros and cons. For instance, Unitils
allows you to use merged datasets, whereas the in-house framework provides EL sup-
port. Another major difference is that Unitils automatically manages the transaction.
From the tools analyzed, Unitils is the only one currently supporting DbUnit,
although Mycila seems to have plans to provide a DbUnit plug-in in the near future.
19.4
Assertions made easy
Having a powerful toolbox of assertion methods readily available is an important asset
in test case development. Why? For two main reasons: productivity and clarity.
When you're writing a test case, your focus is on the test case logic; assertions are
just an accessory. For example, if you need to assert that a variable is greater than a
certain number, your first instinct is to write something like
assertTrue(x>42)
. Such
assertions work fine when the condition holds true, but when it fails, all you get is a
junit.framework.AssertionFailedError:
null
message, which is far from clear. A
second approach would be to include a message in the assertion, such as
assert-
True("X
should
be
greater
than
42,
but
it
is
"+x,
x>42)
. Sure, the clarity is
improved but at the cost of productivity: you now need to create a long string, which
contains the name of the variable (
X
), the operand (
greater
), and the current value
concatenated, which is not only boring but also error prone. A better approach would
be to have an assertion method specialized in comparisons, which would make it as
simple as
assertGreaterThan(x,
42)
.
JU
nit provides a handful of assertions out of the box through the
org.junit.
Assert
class, and although such features cover the basic needs, they come up short
in some particular cases, such as comparing collections or properties in a JavaBean
(not to mention the example in the previous paragraph). Fortunately, many third-
party libraries provide complementary assertions, and in this section we analyze a
few of them.
19.4.1
JUnit-addons assertions package
JU
nit-addons provides a bunch of
XXX
Assert
classes (such as
ListAssert
and
FileAssert
) in the
junitx.framework
package, and each of them provides static
methods aimed to assert specific objects. Although some of the assertion features
they offer are now present in
JU
nit 4.x,
10
some are still surprisingly missing. For
instance,
JU
nit's
Assert
class provides
assertTrue()
,
assertFalse()
, and
assert-
Equals()
methods, but there isn't an
assertNotEquals()
method, which is pro-
vided by
JU
nit-addons'
Assert
.
Let's start with our prologue example, comparing a variable to a number. For that
purpose,
JU
nit-addons offers the
ComparableAssert
class, which provides methods to
10
Such as the
AssertArray
class, whose methods provides the same functionality as
Assert.assert-
ArrayEquals()
.