官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 新余市| 宝坻区| 上高县| 达孜县| 株洲市| 慈利县| 镇平县| 清苑县| 前郭尔| 耒阳市| 伊吾县| 舞阳县| 台安县| 襄樊市| 手游| 札达县| 烟台市| 漳州市| 司法| 通化县| 天柱县| 元氏县| 阿鲁科尔沁旗| 西盟| 隆化县| 龙门县| 甘肃省| 尉犁县| 沁源县| 嘉兴市| 巨野县| 宁明县| 定远县| 长寿区| 中江县| 黄梅县| 衡东县| 商都县| 多伦县| 张掖市| 洛南县|