EasyMock

EasyMock is an alternative mocking framework. It is very similar to Mockito. However, the main difference is that EasyMock does not create spy objects but mocks. Other differences are syntactical.

Let's see an example of EasyMock. We'll use the same set of test cases as those that were used for the Mockito examples:

@RunWith(EasyMockRunner.class) 
public class FriendshipsTest { 
  @TestSubject 
  FriendshipsMongo friendships = new FriendshipsMongo(); 
  @Mock(type = MockType.NICE) 
  FriendsCollection friends;
}

Essentially, the runner does the same as the Mockito runner:

@TestSubject 
FriendshipsMongo friendships = new FriendshipsMongo(); 
 
@Mock(type = MockType.NICE) 
FriendsCollection friends; 

The @TestSubject annotation is similar to Mockito's @InjectMocks, while the @Mock annotation denotes an object to be mocked in a similar fashion to Mockito's @Mock. Furthermore, the type NICE tells the mock to return empty.

Let's compare one of the asserts we did with Mockito:

@Test 
public void mockingWorksAsExpected() { 
  Person joe = new Person("Joe"); 
  expect(friends.findByName("Joe")).andReturn(joe); 
  replay(friends); 
  assertThat(friends.findByName("Joe")).isEqualTo(joe); 
} 

Besides small differences in syntax, the only disadvantage of EasyMock is that the additional instruction replay was needed. It tells the framework that the previously specified expectation should be applied. The rest is almost the same. We're specifying that friends.findByName should return the joe object, applying that expectation and, finally, asserting whether the actual result is as expected.

In the EasyMock version, the second test method that we used with Mockito is the following:

@Test 
public void joeHas5Friends() { 
  List<String> expected = 
Arrays.asList("Audrey", "Peter", "Michael", "Britney", "Paul"); Person joe = createMock(Person.class); expect(friends.findByName("Joe")).andReturn(joe); expect(joe.getFriends()).andReturn(expected); replay(friends); replay(joe); assertThat(friendships.getFriendsList("Joe")) .hasSize(5)
.containsOnly("Audrey", "Peter", "Michael", "Britney", "Paul"); }

Again, there are almost no differences when compared to Mockito, except that EasyMock does not have spies. Depending on the context, that might be an important difference.

Even though both frameworks are similar, there are small details that make us choose Mockito as a framework, which will be used throughout this book.


Visit http://easymock.org/ for more information about this asserts library.

The complete source code can be found in the FriendshipsMongoEasyMockTest class in the https://bitbucket.org/vfarcic/tdd-java-ch02-example-junit repository.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.199.138