Imagine, I have following class:
public class TestClass {
public class Index<X> {
}
public class IndexData {
private final Index<?> index;
private final ReentrantReadWriteLock lock =
new ReentrantReadWriteLock();
public IndexData(final Index<?> index) {
super();
this.index = index;
}
public Index<?> getIndex() {
return index;
}
public Lock getReadLock() {
return lock.readLock();
}
public Lock getWriteLock() {
return lock.writeLock();
}
}
public void add(final InputClass input)
{
final IndexData index = getIndex(input);
final Lock lock = index.getWriteLock();
lock.lock();
try {
// Do something here, which requires synchronization
} finally {
lock.unlock();
}
}
protected IndexData getIndex(final InputClass input) {
// Some logic of getting the index for input
return null;
}
}
I want to write a unit test, which verifies that
- in the
add
method,index.getWriteLock()
is used (notindex.getReadLock()
), - the lock is taken and
- released.
Using Mockito I can write a test like this:
@Test
public void testAddUsesWriteLock() {
// Prepare
final TestClass objectUnderTest = Mockito.spy(new TestClass());
final InputClass input = Mockito.mock(InputClass.class);
final IndexData indexData = Mockito.mock(IndexData.class);
Mockito.doReturn(indexData).when(objectUnderTest).getIndex(input);
final Lock lock = Mockito.mock(Lock.class);
Mockito.doReturn(lock).when(indexData).getWriteLock();
// Invoke method under test
objectUnderTest.add(input);
// Verify
Mockito.verify(indexData).getWriteLock();
Mockito.verify(indexData, Mockito.never()).getReadLock();
Mockito.verify(lock).lock();
Mockito.verify(lock).unlock();
}
How can I do the same thing with EasyMock?
Concrete: How can I the getIndex
method return a mock in EasyMock (line Mockito.doReturn(indexData).when(objectUnderTest).getIndex(input)
) ?
Note: You can find the code of this example here .