EasyMock TestNG Example
We will build up our EasyMock TestNG example from the earlier tutorial. First of all, we will have to add the TestNG dependency to the already existing EasyMock example project.
1 2 3 4 5 6 7 8 |
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> <scope>test</scope> </dependency> |
Here is a simple example where I am mocking ArrayList and stubbing its behaviors. Then I am using TestNG assertions to write some test cases.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.journaldev.easymock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.mock; import static org.easymock.EasyMock.replay; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import org.testng.annotations.Test; public class EasyMockMethodTestNGExample { @Test public void test() { ArrayList<Integer> mockList = mock(ArrayList.class); expect(mockList.add(10)).andReturn(true); expect(mockList.add(20)).andReturn(true); expect(mockList.size()).andReturn(2); expect(mockList.get(0)).andReturn(10); replay(mockList); mockList.add(10); mockList.add(20); assertTrue(mockList.get(0) == 10); assertEquals(mockList.size(), 2); } } |
EasyMock TestNG Annotations Example
Let’s look at another example where I will use EasyMock annotations with TestNG annotations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.journaldev.easymock; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals; import org.easymock.EasyMockSupport; import org.easymock.Mock; import org.easymock.TestSubject; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.journaldev.utils.Calculator; import com.journaldev.utils.MathUtils; public class EasyMockAnnotationTestNGExample { @Mock private Calculator mockCalculator; @TestSubject private MathUtils mathUtils = new MathUtils(mockCalculator); @BeforeMethod public void setup() { EasyMockSupport.injectMocks(this); } @Test public void test() { expect(mockCalculator.add(1, 1)).andReturn(2); expect(mockCalculator.multiply(10, 10)).andReturn(100); replay(mockCalculator); assertEquals(mathUtils.add(1, 1), 2); assertEquals(mathUtils.multiply(10, 10), 100); } } |
Summary
EasyMock integrates very easily with the TestNG framework just like JUnit. Actually, it’s very easy to switch between TestNG and JUnit while working with the EasyMock mocking framework. All we need is to change few import statements for assertions and testing lifecycle and callback methods.