Java Reference
In-Depth Information
19.4.4
Mycila extend assertions
Mycila also provides a module for assertions, which uses a Hamcrest-like style similar
to FEST , as shown in the examples at the project's wiki page ( http://code.google.com/
p/mycila/wiki/ExtendedAssertions) . Unfortunately though, this module was not
widely available at the time the topic was written, so we had to skip it. But it's a project
that's worth watching.
As you can see in this section, custom assertions are provided by many tools. What-
ever your assertion needs are, most likely one (or more) of these tools supports it. And
by using them, you can easily increase the productivity and/or clarity of the failure
messages. The gain might sound small, but every small improvement adds up when
you write hundreds or even thousands of test cases.
19.5
Using reflection to bypass encapsulation
Ideally, test cases should not know anything about the internal state of the test
objects. But the truth is, even in a perfect world where classes were designed with
good encapsulation and testability in mind, sometimes it's still necessary to bypass
encapsulation and access internal members. With the advent of dependency injec-
tion ( DI ) containers such as Spring and Java EE 5 application servers, it's common to
have attributes defined as private without any getter or setter, only a Java annotation
(like @Resource or @Autowired ), which is the hint for the container to inject the
dependency at runtime.
When fields of tested objects are private, most likely they will be accessed through
reflection later on by some framework class. So, instead of complaining about privacy
concerns, why don't you play by the same rules and use reflection to access these fields
in the test cases?
For instance, the UserFacadeImpl object defined in listing 19.4 has a private refer-
ence to a UserDao , and so far this reference could be set only through a public
setUserDao() method. But if that method isn't available, we could use reflection to
access it instead. In this section we show how to do so, first using an in-house utility
class and then analyzing two tools that provide such features for free.
19.5.1
In-house alternative
If you eventually need to set a private field in an object being tested, your first attempt
might be using the reflection API directly in the test method. This isn't a good
approach, though, because the API is cumbersome to use, and most likely such a need
will arise in other test cases. In situations like this, it's better to add a new method to
an existing utility class or create a new one if none exists yet. This particular method
requires three parameters: a reference to the object whose field will be set, the name
of the field, and its new value. And because you'll probably need to get the value of
the field at some point, why not add a helper method for that as well? Listing 19.8
shows these two methods.
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search