Thomas
Thomas

Reputation: 480

Test a class that calls static wrapper methods

I have a static wrapper class for the android Log.

It looks like this (simplified):

// Source: https://github.com/ccrama/Slide/blob/master/app/src/main/java/me/ccrama/redditslide/util/LogUtil.java
public class LogUtil {
    private static final int CALLING_METHOD_INDEX;    

    static {
        int i = 1;
        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            i++;
            if (ste.getClassName().equals(LogUtil.class.getName())) {
                break;
            }
        }
        CALLING_METHOD_INDEX = i;
    }

    public static String getTag() {
        final StackTraceElement ste = Thread.currentThread().getStackTrace()[CALLING_METHOD_INDEX];
        return "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
    }

    public static void v(String message) {
        Log.v(getTag(), message);
    }
}

My problem: I'm testing another method that calls this LogUtil.v()'s method.

Is there a way to test the other method with Mockito and not Powermock(ito) if possible?

Currently it throws a LogUtil.v not mocked Exception.

I read that if I have to use PowerMockito, I'm doing something wrong (=> not following TDD).

Upvotes: 2

Views: 1224

Answers (1)

GhostCat
GhostCat

Reputation: 140573

( disclaimer: I am one of those folks telling people to not use PowerMock(ito) )

Having said so: when you are using a 3rd party library, which you can't change, then using PowerMock(ito) can be a reasonable option.

In essence, you only got two options:

  • As said; go for the frameworks that allow mocking static methods; and that allow you to prevent such static init code to be executed within your unit-test environment. There is PowerMock(ito), and also JMockit.
  • Alternatively, you could build a small tiny wrapper around these classes; and then make sure that all your own code only works with those wrappers.

Thus you have to evaluate the pros/cons of both approaches; and pick the one that "works better" for you and your team. Me, personally, always go for option 2. But of course, that is only possible when writing new code.

In reality, a massive refactoring of the whole code-base in order to replace those static calls with your own wrapper is not something that should be approached lighthearted.

Upvotes: 1

Related Questions