mockito support for mocking constructors

521 views
Skip to first unread message

Joe Kearney

unread,
Jun 24, 2009, 10:42:46 AM6/24/09
to powe...@googlegroups.com
Hi,

Is there support in PowerMock 1.2.5 for mocking the new operator on a target class with Mockito, or is this part of the pile of stuff waiting for 1.3? I see it can be done with the EasyMock integrations, but it doesn't look like this is available for Mockito yet. Unless I misunderstood some of the static/partial mocking support, perhaps?

Thanks,
Joe

Jeff Szeto

unread,
Jun 24, 2009, 1:40:23 PM6/24/09
to powe...@googlegroups.com
Joe,

Mocking new operator can still be done with curent 1.2.5 version along with Mockito.  However, having said that, the semantic of setting up and verifying behavior is a mix of EasyMock and Mockito, so hopefully that could be improved in 1.3 version. 

Basically, you still need to use PowerMock.expectNew() along with PowerMock.replay() to mock out new operator, but the actual mock object returned by PowerMock.expectNew().thenReturn() can be created by Mockito and thus setup with Mockito semantic.  Here is a test I put together to show what I meant:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TestNewConstructor.class)
public class TestNewConstructor {
    
    public String methodCallNew() {
        ConstructorDemo test = new ConstructorDemo("abc");
        return test.getParam(); // should be always abc
    }

    @Test
    public void testMockNewOperator() throws Exception {
        String expectedValue = "mocked value";
        // we use mockito to setup behavior of returned object
        ConstructorDemo mock = Mockito.mock(ConstructorDemo.class);
        Mockito.when(mock.getParam()).thenReturn(expectedValue);
        // we use expectNew to return the mockito-created object
        PowerMock.expectNew(ConstructorDemo.class, "abc").andReturn(mock);
        
        PowerMock.replayAll();
        TestNewConstructor test = new TestNewConstructor();
        Assert.assertEquals(expectedValue, test.methodCallNew());
        PowerMock.verifyAll();
    }
}

public class ConstructorDemo {
    
    private String param = "default";
    
    public ConstructorDemo(String param) {
        System.out.println("Real Constructor Called: " + param);
        this.param = param;
    }
    
    public String getParam() {
        return param;
    }
}

I hope that helps.

Thanks,
Jeff
Reply all
Reply to author
Forward
0 new messages