Java Reference
In-Depth Information
final
ConnectionFactory factory =
context.mock( ConnectionFactory.class );
final
InputStream mockStream = context.mock( InputStream.class );
context.checking(
new
Expectations()
{
{
oneOf( factory ).getData();
will( returnValue( mockStream ) );
oneOf( mockStream ).read();
will( returnValue( -1 ) );
oneOf( mockStream ).close();
will( throwException(
new
IOException( "cannot close" ) ) );
}
} );
I
J
WebClient2 client =
new
WebClient2();
String result = client.getContent( factory );
assertNull( result );
}
}
Once again, we start the test case by instructing
JU
nit to use the
JM
ock test runner
B
. This will save us the explicit verification of the expectations. To tell
JM
ock to cre-
ate mock objects not only for interfaces but also for classes, we need to set the
imposteriser
property of the context
C
. That's all; now we can continue creating
mocks the normal way. In
D
we declare and initialize the two objects we'd like to
create mocks of. In
E
we start the declaration of the expectations. Notice the fine
way we declare the consecutive execution of the
read()
method of the stream
F
and also the returned values. In
G
we call the method under test, and in
H
we
assert the expected result.
For a full view of how to use the
JM
ock mocking library, we also provide another
@Test
method, which tests our
WebClient
under exceptional conditions. In
I
we
declare the expectation of the
close()
method being triggered, and in
J
we instruct
JM
ock to raise an
IOException
when this trigger happens.
As you can see, the
JM
ock library is as easy to use as the EasyMock one. Whichever
you prefer to use is up to you, as long as you remember that what increases your soft-
ware quality isn't the framework you use but rather how much you use it.
7.7
Summary
This chapter described a technique called
mock objects
that lets you unit test code in
isolation from other domain objects and from the environment. When it comes to
writing fine-grained unit tests, one of the main obstacles is to extract yourself from
the executing environment. We've often heard the following remark: “I haven't
tested this method because it's too difficult to simulate a real environment.” Well, not
any longer!