Mocking java object for unit test
Try Mockito and you will love it!
You can take a look at this library in this post showing 6 simple examples of using Mockito.
A short example:
@Test
public void iteratorWillReturnHelloWorld(){
//arrange
Iterator i = mock(Iterator.class);
when(i.next()).thenReturn("Hello").thenReturn("World");
//act
String result = i.next() + " " + i.next();
//assert
assertEquals("Hello World", result);
}
Change your requirements:
It seems that Mockito works fine on Java 1.4 and JUnit 3 as indicated in this report.
Same example as above, but for Java 1.4:
public void testIteratorWillReturnHelloWorld(){
//arrange
Iterator i = Mockito.mock(Iterator.class);
Mockito.when(i.next()).thenReturn("Hello").thenReturn("World");
//act
String result = i.next() + " " + i.next();
//assert
assertEquals("Hello World", result);
}
source to share
There are a number of ridiculous libraries in Java:
- EasyMock is arguably the most popular mocking library at the moment. Wide range of functions, easy to use.
- Mockito , originally based on EasyMock code, uses similar paradigms for mocking, but automates several tasks such as switching the states of mocks (namely, record, play, check, reset)
- jMock mocking based on Hamcrest matches. Haven't personally used this one, but from what I get it, it's at least decent.
... and most likely some other less-used libraries that I haven't even heard of.
Since your requirement is JDK 1.4.2 support , unfortunately you can choose the old version of EasyMock or the really old version of jMock. Even Java5 support will end in two days ( October 30, 2009, that is! ), If possible, try moving out of the 1.4.2 era - you (and / or your company) are just far behind others and beyond any serious technical support.
source to share