How to mock method e in Log How to mock method e in Log android android

How to mock method e in Log


This worked out for me. I'm only using JUnit and I was able to mock up the Log class without any third party lib very easy. Just create a file Log.java inside app/src/test/java/android/util with contents:

package android.util; public class Log {    public static int d(String tag, String msg) {        System.out.println("DEBUG: " + tag + ": " + msg);        return 0;    }    public static int i(String tag, String msg) {        System.out.println("INFO: " + tag + ": " + msg);        return 0;    }    public static int w(String tag, String msg) {        System.out.println("WARN: " + tag + ": " + msg);        return 0;    }    public static int e(String tag, String msg) {        System.out.println("ERROR: " + tag + ": " + msg);        return 0;    }    // add other methods if required...}


You can put this into your gradle script:

android {   ...   testOptions {        unitTests.returnDefaultValues = true   }}

That will decide whether unmocked methods from android.jar should throw exceptions or return default values.


If using Kotlin I would recommend using a modern library like mockk which has built-in handling for statics and many other things. Then it can be done with this:

mockkStatic(Log::class)every { Log.v(any(), any()) } returns 0every { Log.d(any(), any()) } returns 0every { Log.i(any(), any()) } returns 0every { Log.e(any(), any()) } returns 0