Log messages in android studio junit test

前端 未结 4 1737
余生分开走
余生分开走 2020-12-30 03:25

Is there a way to print out Logcat (Log.i, Log.d) messages when running a JUnit (method) test in Android Studio?

I can see System.out.print message but no logcat pri

4条回答
  •  悲哀的现实
    2020-12-30 03:53

    I was searching for this same thing and didn't ever find a straight answer. I know this question is over a year old but still, it'd be good to have an answer here for future reference.

    The android.util.Log class logs directly to Logcat and the implementation for android.util.Log is not available when running the unit tests on the local JVM. You'll receive an error when trying to use the Log class in your unit tests because "the android.jar file used to run unit tests does not contain any actual code (those APIs are provided only by the Android system image on a device)."
    See Android Documentation on Unit Testing

    So if you really want to use android.util.Log you'll need to mock it locally and utilize System.out.print to print to the console. To start, add PowerMockito to your project. If you're using Gradle, you can just add the following dependencies:

    testCompile 'junit:junit:4.12'
    testCompile 'org.powermock:powermock:1.6.5'
    testCompile 'org.powermock:powermock-module-junit4:1.6.5'
    testCompile 'org.powermock:powermock-api-mockito:1.6.5'
    

    Next I used Steve's answer here to figure out how to return a parameter passed into a mock object using Mockito.

    The result was something like:

    import android.util.Log;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.invocation.InvocationOnMock;
    import org.mockito.stubbing.Answer;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    import static org.mockito.Matchers.anyString;
    import static org.powermock.api.mockito.PowerMockito.when;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({Log.class})
    public class SomeUnitTest {
    
        @Test
        public void testSomething() {
            System.out.println("Running test"); 
            PowerMockito.mockStatic(Log.class);
    
            // Log warnings to the console        
            when(Log.w(anyString(), anyString())).thenAnswer(new Answer()      {
                @Override
                public Void answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    if (args.length > 1) { //cause I'm paranoid
                        System.out.println("Tag:" + args[0] + " Msg: " + args[1]);
                    }
                    return null;
                }
            });
            Log.w("My Tag", "This is a warning");
        }
    }
    

    Hope this helps someone!

提交回复
热议问题