Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mock a super class method call?

Sometimes, you want to test a class method and you want to do an expectation on a call of a super class method. I did not found a way to do this expectation in java using easymock or jmock (and I think it is not possible).

There is a (relative) clean solution, to create a delegate with the super class method logic and then set expectations on it, but I don't know why and when use that solution ¿any ideas/examples?

Thanks

like image 809
arielsan Avatar asked Mar 07 '09 23:03

arielsan


People also ask

Can we mock super class method?

It's up to you whether you want to mock or not the getMsg() method in Junit test class. When you mock the getMsg() method then it will return the mocked value from getWelcomeMsg() otherwise it will return the actual value.

Can you call a method from a superclass?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

Can we call super class method in subclass?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.


1 Answers

Well, you can if you want to. I don't know if you are familiar with JMockit, go check it out. The current version is 0.999.17 In the mean time, let's take a look at it...

Assume the following class hierarchy:

public class Bar {
    public void bar() {
        System.out.println("Bar#bar()");
    }
}

public class Foo extends Bar {
    public void bar() {
        super.bar();
        System.out.println("Foo#bar()");
    }
}

Then, using JMockit in your FooTest.java you can validate that you're actually making a call to Bar from Foo.

@MockClass(realClass = Bar.class)
public static class MockBar {
    private boolean barCalled = false;

    @Mock
    public void bar() {
        this.barCalled = true;
        System.out.println("mocked bar");
    }
}

@Test
public void barShouldCallSuperBar() {
    MockBar mockBar = new MockBar();
    Mockit.setUpMock(Bar.class, mockBar);

    Foo foo = new Foo();
    foo.bar();

    Assert.assertTrue(mockBar.barCalled);

    Mockit.tearDownMocks();
}
like image 129
Cem Catikkas Avatar answered Sep 30 '22 20:09

Cem Catikkas