5

I come from the PHP testing world and i'm starting testing in Java.

I've seen several tools to mock the SUT in JUnit, like Mockito, SevenMock, ClassMock, etc.

I really appreciate any recommendation of which one should i use.

Thanks in advance!

victorgp
  • 882
  • 1
  • 13
  • 22

3 Answers3

8

I've used Mockito quite a lot. http://mockito.org/ I have not used EasyMock so cant say much about it.

Using Mockito is straightforward but the classes that you intend to test should also be in a decoupled state which will make it easier to test. With mockito you are instantiating a particular class with mocks objects.

Say you got a class that you want to test, but want to mock one of its dependencies

final DepedencyToMockClass mockObject = mock(DepedencyToMockClass.class);
when(mockObject.getTestMethod()).thenReturn("Test");

Now this mockObject can now be injected when initializing your intended class.

final ClassToTest test = new ClassToTest(mockObject);

Mockito uses reflection to create these mock objects. However if you have a dependency and if it is declared final then mocking will fail.

Another useful method in Mockito is verify where you can verify certain operations in your mock objects. Have a peep at mockito. However there are limitations in mock objects, in some cases it will be hard to create mock objects perhaps external/third party code. I think it's good practise to attempt to instantiate real objects when injecting them for testing purposes, failing which Mockito helps.

MalsR
  • 1,197
  • 1
  • 12
  • 23
3

I've been using JMock for a while. I personally like that the resulting code is easy to read, and you can easily differentiate between allowances and expectations:

context.checking(new Expectations() {{
        // allowances
        ignoring(parserState);
        allowing(factory).create(); will(returnValue(object));

        // expectations
        one(service).addSth(with(any(Integer.class)), with(sth));
    }});

Other powerful features are:

  • Sequences: invocations in sequence.
  • Argument matchers: hamcrest library
  • States: constraint invocations when a condition is true.
djodar
  • 45
  • 6