behelit behelit - 26 days ago 7
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

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

@Test
public void testLogConsoleInfo()
{
PowerMockito.mockStatic(Log.class);

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

PowerMockito.verifyStatic(Mockito.times(1));
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 Log.wtf(...) it still passes. I would have assumed that it should fail since Log.wtf 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

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:

@RunWith(PowerMockRunner.class)
@PrepareForTest(android.util.Log.class) 
public class LoggerUnitTest {
    @Test
    public void testLog() throws Exception
    {
        PowerMockito.mockStatic(Log.class); //        when(Log.e(anyString(), anyString())).thenReturn(1);

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

        PowerMockito.verifyStatic(times(1));
        Log.e(anyString(), anyString());
    } }