Shai M.
Shai M.

Reputation: 1314

EasyMock - override an object creation

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
}

Upvotes: 1

Views: 2775

Answers (3)

GhostCat
GhostCat

Reputation: 140633

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.

Upvotes: 2

Sravya
Sravya

Reputation: 159

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

Upvotes: -1

user5287318
user5287318

Reputation:

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
}

Upvotes: 1

Related Questions