Thursday, February 11, 2010

Using Powermock to Mock Java Objects for Unit Testing

This test uses the EasyMock style (as opposed to Mockito style), so it needed the corresponding file download. The code sample (click on view source icon to see it better):
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.legacy.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Person.class })
public class PersonResourceTest {

    @Test
     public void testPost() {

        Person personMock = createMock(Person.class);
        expect(personMock.getName()).andReturn("Jon Smith");
        replay(personMock);

    // do the test...        

        Assert.assertEquals("Jon Smith", result.name);
    }
    
}

No comments: