Daily Archives: June 8, 2015

Simple easymock example

EasyMock can mock an interface, or class. In this way, we can test our code without implementing them. In order to use the static functions in easyMock, we can either extend it, or use “import static” key word. I think using “import static” key word is more general. Let’s start review the code.

main/java — foo.bar.MyInterface

package foo.bar;

/**
 * Created by lipeng on 6/8/2015.
 */
public interface MyInterface {
    int getNum();
}

test/java — foo.bar.TestDrive

package foo.bar;

import static org.easymock.EasyMock.*;  //import static functions
import static org.junit.Assert.*;   //import static functions
import org.junit.Before;
import org.junit.Test;

/**
 * Created by lipeng on 6/5/2015.
 */
public class TestDrive {

    private MyInterface myInterface;

    @Before
    public void setUp(){
        myInterface = createNiceMock(MyInterface.class);
    }

    @Test
    public void testCalc1(){
        expect(myInterface.getNum()).andReturn(100);
        replay(myInterface);    //make mock object ready to use
        assertEquals(100, myInterface.getNum());
    }

}