Java Reference
In-Depth Information
assertEquals( "The return string must match 'showAlbumDetails'",
forwardString, "showAlbumDetails" );
assertNotNull( "The album must not be null",
albumDetailsBean.getAlbum() );
assertEquals( "The author must be U2",
albumDetailsBean.getAlbum().getAuthor(), "U2" );
assertEquals( "The year of the album must be 1991",
albumDetailsBean.getAlbum().getYear(), 1991 );
}
@Test
public void
testShowAlbumDetailsNoParameterAlbum() {
context.checking(
new
Expectations() {
{
oneOf( mockRequest ).getParameter( "albumName" );
will( returnValue( null ) );
}
} );
I
AlbumDetailsBean albumDetailsBean =
new
AlbumDetailsBean();
albumDetailsBean.setRequest( mockRequest );
String forwardString = albumDetailsBean.showAlbumDetails();
assertEquals( forwardString, "" );
assertNull( "The album must be null",
albumDetailsBean.getAlbum() );
}
@Test
public void
testShowAlbumDetailsNoRealAlbum() {
context.checking(
new
Expectations() {
{
oneOf( mockRequest ).getParameter( "albumName" );
will( returnValue( "No-real-album" ) );
}
} );
AlbumDetailsBean albumDetailsBean =
new
AlbumDetailsBean();
albumDetailsBean.setRequest( mockRequest );
String forwardString = albumDetailsBean.showAlbumDetails();
assertEquals( "The return string must match 'showAlbumDetails'",
forwardString, "showAlbumDetails" );
assertNull( "The album must be null", albumDetailsBean.getAlbum() );
}
}
This test should be simple if you've already read chapter 7. We start by defining the
Mockery
context
B
and the object that we want to mock
C
. After that, in the
@Before
method we initialize the request object to be ready for usage
D
. The next step defines
several test methods, each of which will test the
showAlbumDetails
method by specify-
ing a different parameter in the request. For each of those methods we define the
expectations
E
, initialize
AlbumDetailsBean
F
, set the mock request to the bean
G
,
and execute the method under test
H
. The final test is to perform the assertions that
we want
I
.