EasyMock - override an object creation

喜夏-厌秋 提交于 2021-01-29 18:06:19

问题


How can I override an object creation inside a method?

public class ClassToTest {
    public Object testMethod() {
        ... code ...
        Object result;
        try {
            result = new ClassToMock(someParam).execute();
        } catch (Exception e) {
            // handle error
        }

        return result;
    }
}

How can my test override the "execute" method of ClassToMock? I will be happy for code examples with EasyMock. I want to test "testMethod", something like:

@Test
public void testMethodTest(){
    ClassToTest tested = new ClassToTest();
    // Mock ClassToMock somehow
    tested.testMethod();
    // Verify results
}

回答1:


Simply spoken: that doesn't work.

You can't mock calls to new (using EasyMock. It is possible using frameworks like PowerMock(ito) or JMockit though).

But the better way: use dependency injection in order to pass already created objects into your class under test.

To be more precise: if your class really doesn't need any other objects to work, then a test would more look like

 @Test
 public void testFoo() {
    ClassToTest underTest = new ClassToTest(...)
    underTest.methodToTest();
    assertThat( ... )

In other words: in order to test your class, you simply instantiate it; then you call methods on it; and you use asserts to check the expected states of it.

See here for excellent (although a bit lengthy) explanations on what I am talking about.




回答2:


It is only possible to override methods if the method of the class is not marked as final

try {
    ClassToMock mock = new ClassToMock(someParam){
        public Object execute(){ //Such that your method is public
            //If you want to call back to the pure method
            //super.execute()

            //Do override things here
        }
    };
    result = mock.execute();
} catch (Exception e) {
    // handle error
}



回答3:


It is possible with Powermock. Using powermock, you can mock 'new' operator as well

ClassToMock mock = PowerMock.createMock(ClassToMock.class);
PowerMock.expectNew(ClassToMock.class, parameterValues).andReturn(mock);
PowerMock.replayAll();

For more details please refer this link



来源:https://stackoverflow.com/questions/38180541/easymock-override-an-object-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!