Mocking java object for unit test

I'm looking for a good unit test framework that I can use to fetch private methods that can run in JDK 1.4.2 .

Greetings,

+2


source to share


5 answers


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);
}

      

+11


source


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.

+3


source


Why don't you try Easymock or Mockito

+2


source


I am using jUnit with jMock

+1


source


Nobody took it, but why are you trying to mimic private methods? This is almost always a bad idea as it destroys encapsulation.

+1


source







All Articles