behelit
behelit

Reputation: 1793

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?

Upvotes: 3

Views: 4837

Answers (2)

anthropic android
anthropic android

Reputation: 364

For the RobolectricGradleTestRunner, the following incantation would have exposed your logging: ShadowLog.stream = System.out Robolectric does not print the Android system logging by default.

It's also worth noting that the RobolectricGradleTestRunner has been deprecated in favor of the fully operational RobolectricTestRunner (The above assignment is still effective)

Upvotes: 0

behelit
behelit

Reputation: 1793

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());
    } }

Upvotes: 6

Related Questions