Java Reference
In-Depth Information
That worked because the phone number type converter doesn't use
anything other than the
String
input and the list of errors that we pro-
vide, both of which are simple to create. But what about a class that
depends on objects that are not so easy to create, such as the
MyLo-
calePicker
, which needs an
HttpServletRequest
and an
HttpSession
?
package
stripesbook.ext;
public class
MyLocalePicker
extends
DefaultLocalePicker {
public static final
String LOCALE = "locale";
@Override
public
Locale pickLocale(HttpServletRequest request) {
HttpSession session = request.getSession();
// Look in the request.
String locale = request.getParameter(LOCALE);
if
(locale !=
null
) {
session.setAttribute(LOCALE, locale);
}
// Not found in the request? Look in the session.
else
{
locale = (String) session.getAttribute(LOCALE);
}
// Use the locale if found.
if
(locale !=
null
) {
return new
Locale(locale);
}
// Otherwise, use the default.
return super
.pickLocale(request);
}
}
Say we wanted to test the
pickLocale
( ) method according to different
scenarios of what's in the request and what's in the session. It's not so
simple to create mock implementations of
HttpServletRequest
and
HttpSes-
sion
. Many libraries exist to help us avoid having to create mock objects
by hand. One such library is Mockito, available at
http://www.mockito.
or class. When we mock an interface or a class, for example, Mockito
will create a mock on the fly that responds to methods without throwing
any exceptions. Furthermore, we can instruct Mockito to return specific
values from method calls so that we can set up the mock according to
the test we want to execute.
Let's see how that works to test
MyLocalePicker
. Say we wanted to test
that
pickLocale
( ) returns the French locale if the
locale=fr
request para-
Search WWH ::
Custom Search