Java Reference
In-Depth Information
JUnit best practices: EasyMock object creation
Here is a nice-to-know tip on the createMock method. If you check the API of Easy-
Mock, you'll see that the createMock method comes with numerous signatures.
The signature that we use is
createMock(String name, Class claz);
But there's also
createMock(Class claz);
So which one should you use? The first one is better. If you use the second one and
your expectations aren't met, then you'll get an error message like the following:
java.lang.AssertionError:
Expectation failure on verify:
read(): expected: 7, actual: 0
As you can see, this message isn't as descriptive as we want it to be. If we use
the first signature instead, and we map the class to a given name, we get some-
thing like the following:
java.lang.AssertionError:
Expectation failure on verify:
name.read(): expected: 7, actual: 0
To be able to mock the InputStream class, we're going to use the Class Extension of
EasyMock. Class Extension is an extension project of EasyMock that lets you generate
mock objects 4 for classes and interfaces. You can download it separately from the Easy-
Mock website.
Listing 7.16
Reworking the WebClient test using EasyMock
[...]
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
B
public class TestWebClientEasyMock
{
private ConnectionFactory factory;
private InputStream stream;
C
@Before
public void setUp()
{
factory = createMock( “factory”, ConnectionFactory. class );
stream = createMock( “stream”, InputStream. class );
}
D
4
Final and private methods can't be mocked.
 
 
 
Search WWH ::




Custom Search