How to handle logging in Android JUnit tests?

I would like to write information to model classes - not necessarily for unit testing purposes, but for real-life scenarios where I am trying to debug.

However, if I try to use methods android.util.Log, I get the following errors when running JUnit tests:

java.lang.RuntimeException: Method d in android.util.Log not mocked. See http://g.co/androidstudio/not-mocked for details.

I understand why this is happening, I should not use the Android frame code in model classes that should be structure independent! I do not mind the error, but I am trying to find a way around this.

I have one idea, does this make sense?

Create a class CustomLogin the following lines:

public class CustomLog {
    private static ILogger mLogger;

    public static void setLogger(ILogger logger) {
        mLogger = logger;
    }

    public static void e(String tag, String message) {
        mLogger.e(tag, message);
    }
}

Where ILoggeris the interface with the necessary methods for performing log functions (e, d methods, etc.)

ILoggerImpl, android.util.Log, MockLogger, System.out.println / ( - !).

, ( CustomLog , ).

, - / , , , , / android.util.Log.

, " ", ? ?

+4
1

" ", , - PowerMockito Log ging. PowerMockito.mockStatic(Log.class);, , PowerMockito replace() Android.util Log.v, Log.d, Log.i Log.e , System.out.println. Android Studio Run.

String[] logMethods = {"v", "d", "i", "e"};
InvocationHandler systemOutPrintln = new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        StringBuilder messageBuilder = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            String arg = args[i].toString();
            messageBuilder.append(arg);
            // add separators, ASCII art, ...
        }
        System.out.println(messageBuilder);
        return messageBuilder.toString().length();
    }
};

for (String logMethod : logMethods) {
    replace(method(Log.class, logMethod, String.class, String.class)).with(systemOutPrintln);
    replace(method(Log.class, logMethod, String.class, String.class, Throwable.class)).with(systemOutPrintln);
}

: , .

0

Source: https://habr.com/ru/post/1671630/


All Articles