EasyMock is an open-source testing framework for Java released under the Apache License. The framework allows the creation of test double objects for the purpose of Test-driven Development TDD or Behavior Driven Development BDD.
A research performed in 2013 on 10,000 GitHub projects found that EasyMock is the 32nd most popular Java library.
The EasyMock provides dynamically generated Mock objects at runtime, without having to implement them. In EasyMock, the definition of Mock Object is differed from using an implemented Mock Object. Mock objects are built at run time and additional implementations cannot be defined for those objects.
EasyMock was created by Tammo Freese in 2001 at OFFIS. Originally it allowed only mock interfaces with type safe mocking and additional features were added in later developments. Most notably, class mocking was added by Henri Tremblay, the current lead developer, in 2003.
EasyMock can be use in application with often-changing interfaces.
Simple currency exchange program is provided here. An interface may look like as follows:
import java.io.IOException; public interface ExchangeRate { double getRateString inputCurrency, String outputCurrency throws IOException; }
Implementation for a concrete class may look like as follows:
import java.io.IOException; public class Currency { private String units; private long amount; private int cents; public Currencydouble amount, String code { this.units = code; setAmountamount; } private void setAmountdouble amount { this.amount = new Doubleamount.longValue; this.cents = int amount * 100.0 % 100; } public Currency toEurosExchangeRate converter { if "EUR".equalsunits return this; else { double input = amount + cents/100.0; double rate; try { rate = converter.getRateunits, "EUR"; double output = input * rate; return new Currencyoutput, "EUR"; } catch IOException ex { return null; } } } public boolean equalsObject o { if o instanceof Currency { Currency other = Currency o; return this.units.equalsother.units && this.amount == other.amount && this.cents == other.cents; } return false; } public String toString { return amount + "." + Math.abscents + " " + units; } }
Sample implementation for a test class may look like as follows:
import junit.framework.TestCase; import org.easymock.EasyMock; import java.io.IOException; public class CurrencyTest extends TestCase { public void testToEuros throws IOException { Currency testObject = new Currency2.50, "USD"; Currency expected = new Currency3.75, "EUR"; ExchangeRate mock = EasyMock.createMockExchangeRate.class; EasyMock.expectmock.getRate"USD", "EUR".andReturn1.5; EasyMock.replaymock; Currency actual = testObject.toEurosmock; assertEqualsexpected, actual; } }