behelit behelit - 1 year ago 80
Android Question

Android - How to UnitTest a Logging class with mockito

I have written a class to manage logging within an android application project.
The LogManager is basically a wrapper for android.util.log
It handles logging to a file, if the application crashes, and standard debug logging.
I would like to unit test the class using JUnit.

I have tried the following but it does not seem to produce the results I would expect after reading the examples:

LogManager.class (This is a simplified version of the class I have used, for demonstration purposes)

public class LogManager implements ILogManager
public void log(String tag, String message)
Log.e(tag, message);

And here is my test class

@Config(constants = BuildConfig.class, sdk = 21)
@PrepareForTest({Log.class, LogManager.class})
public class LogManagerUnitTest

public void testLogConsoleInfo()

LogManager.getInstance().log(LogLevel.INFO, "test", "test");

Log.e(anyString(), anyString());

My problem is that this passes no matter what I put.
E.g: if I instead replace the last call with it still passes. I would have assumed that it should fail since was not called in the static class Log?
So my question is, why isn't this approach working as expected and what would be the correct way to do it?

Answer Source

I started a fresh project and was able to get it to fail tests and succeed appropriately using the following, so I'm assuming the runwith was the culprit:

public class LoggerUnitTest {
    public void testLog() throws Exception
        PowerMockito.mockStatic(Log.class); //        when(Log.e(anyString(), anyString())).thenReturn(1);

        Logger.log("test", "test");

        Log.e(anyString(), anyString());
    } }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download