zfranciscus
zfranciscus

Reputation: 17085

Mocking java object for unit test

I am looking for a good unit test framework that I can use to mock private methods that can run under JDK 1.4.2.

Cheers,

Upvotes: 2

Views: 7916

Answers (5)

Steve Freeman
Steve Freeman

Reputation: 2707

No-one's picked this up, but why are you trying to mock private methods? It's almost always a bad idea since it breaks encapsulation.

Upvotes: 1

Romain Linsolas
Romain Linsolas

Reputation: 81667

Try Mockito and you will love it!

You can have a look of this library in this blog post, showing 6 simple examples of Mockito usage.

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

Edit regarding your requirements:

It seems that Mockito runs quite well on Java 1.4 and JUnit 3, as stated in this blog post.

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

Upvotes: 11

Esko
Esko

Reputation: 29375

There's a whole range of mocking libraries available for Java:

  • EasyMock, arguably the most popular mocking library at the moment. Wide range of features, easy to use.
  • Mockito, originally based on EasyMock's code, uses similar paradigms for mocking but automates several tasks such as switching mock object states (namely record, replay, verify, reset)
  • jMock, mocking based on Hamcrest Matchers. Haven't personally used this one but from what I've understood, it's at least decent.

...and most likely some other less used libraries I haven't even heard of.

Since your requirement is JDK 1.4.2 support, that unfortunately means you can choose an old version of EasyMock or really old version of jMock. Even Java5's support is going to end in two days (30 October 2009, that is!) so if possible, try to get out from the 1.4.2 era - you (and/or your company) are simply far behind others and outside any kind of serious tech support.

Upvotes: 3

pstanton
pstanton

Reputation: 36689

I use jUnit with jMock

Upvotes: 1

Whiteship
Whiteship

Reputation: 1879

Why don't you try Easymock or Mockito

Upvotes: 2

Related Questions