Java Reference
In-Depth Information
internal information about the class, making them quite powerful. In the examples so
far, we've used them only to emulate real behaviors, but we haven't mined all the
information they can provide.
It's possible to use mocks as probes by letting them monitor the method calls the
object under test makes. Let's take the
HTTP
connection example. One of the inter-
esting calls we could monitor is the close method on the
InputStream
. We haven't
been using a mock object for
InputStream
so far, but we can easily create one and
provide a
verify
method to ensure that
close
has been called. Then, we can call
the
verify
method at the end of the test to verify that all methods that should
have been called were called (see listing 7.13). We may also want to verify that
close
has been called exactly once and raise an exception if it was called more than
once or not at all. These kinds of verifications are often called
expectations
.
DEFINITION
Expectation
—When we're talking about mock objects, an
expecta-
tion
is a feature built into the mock that verifies whether the external class
calling this mock has the correct behavior. For example, a database connec-
tion mock could verify that the
close
method on the connection is called
exactly once during any test that involves code using this mock.
To see an example of an expectation, look at listing 7.13.
Listing 7.13
Mock
InputStream
with an expectation on close
[...]
import
java.io.IOException;
import
java.io.InputStream;
public class
MockInputStream
extends
InputStream {
private
String buffer;
private int
position = 0;
private int
closeCount = 0;
public void
setBuffer(String buffer) {
this
.buffer = buffer;
}
public int
read()
throws
IOException {
if (position ==
this
.buffer.length()) {
return
-1;
}
return this
.buffer.charAt(this.position++);
}
public void
close()
throws
IOException {
closeCount++;
super
.close();
}
public void
verify()
throws
java.lang.AssertionError {
if (closeCount != 1) {
throw new
AssertionError ("close() should "
+ "have been called once and once only");
}
}
}
Tell mock what
read
method
should return
Count number of
times
close
is called
Verify
expectations
are met