How do I mock static methods in a class with easymock?

Suppose I have a class like so:

public class StaticDude{
    public static Object getGroove() {
        // ... some complex logic which returns an object
    };
}

How do I mock the static method call using easy mock? StaticDude.getGroove().

I am using easy mock 3.0


Not sure how to with pure EasyMock, but consider using the PowerMock extensions to EasyMock.

It has a lot of cool functions for doing just what you need - https://github.com/jayway/powermock/wiki/MockStatic


Easymock is a testing framework for "for interfaces (and objects through the class extension)" so you can mock a class without an interface. Consider creating an interfaced object with an accessor for your static class and then mock that acessor instead.

EDIT: Btw, I wouldn't recommend doing static classes. It is better to have everything interfaced if you are doing TDD.


Just in Case PowerMock is unavailable for any reason:

You could move the static call to a method, override this method in the instantiation of the tested class in the test class, create a local interface in the test class and use its method in the overidden method:

private interface IMocker 
{
    boolean doSomething();
}

IMocker imocker = EasyMock.createMock(IMocker.class);

...

@Override
void doSomething()
{
     imocker.doSomething();
}

...

EasyMock.expect(imocker.doSomething()).andReturn(true);

Generally speaking, it is not possible to mock a static method without using some sort of accessor, which seems to defeat the purpose of using a static method. It can be quite frustrating.

There is one tool that I know of called "TypeMock Isolator" which uses some sort of Satanic Magic to mock static methods, but that tool is quite expensive.

The problem is, I know of no way to override a static method. You can't declare it virtual. you can't include it in an interface.

Sorry to be a negative nelly.