EasyMock Hello World
In Object oriented software development mock(Dummy) objects are simulation of real object in controlled ways. This is required when you start unit testing of your classes. Unit test is nothing but testing of your single program which is dependent on other classes. To perform unit test you create mock object to simulate same behavior of real, complex objects, it’s useful when it’s impossible or impractical to incorporate real objects to complete your testing.
EasyMock is testing framework which can be use to create dynamic mock objects it provides mock objects by generating them on fly by using java proxy mechanism. To start with EasyMock let’s first setup everything up and do Hello World testing then we next tutorial we will move on some dummy real time testing.
Note: We will do testing with today’s latest version 3.3.1 which supports mocking classes. If you have experience working with old EasyMock it was not possible to create mock objects for classes and you had to create interface which was causing chaos to to create lots of interfaces before performing real unit testing.
- Create maven java project below is final structure:
- pom.xml to dependency details:
- Class from data comes HelloWorld.java:
- Client class which consume HelloWorld.java:
- EasyMock testing classes to perform unit test:
- I understand what you are thinking, what the heck we doing above. Let me clear this out:
- Here we do create mock object of HelloWorld.class
- Above we have define what EasyMock expect. When it will call helloWorld.printHelloWorld() it will expect return type which is String so we are using andReturn(“Hello World!”) to create mock data.
- Calling EasyMock.replay method makes mock object ready to use.
- On above three lines is self explanatory. We are creating HelloWorodUser object then use assertEquals to compare actual and return value and finally verify it.
Now to run: Right click HelloWorldTest.java –> Run As –> JUnit:
- You will see Unit test got successful:
- For more details please visit EasyMock getting started guide