How to mock method e in Log

后端 未结 12 1709
忘掉有多难
忘掉有多难 2020-12-13 03:24

Here Utils.java is my class to be tested and following is the method which is called in UtilsTest class. Even if I am mocking Log.e method as shown below

 @B         


        
12条回答
  •  孤城傲影
    2020-12-13 03:49

    Using PowerMock one can mock Log.i/e/w static methods from Android logger. Of course ideally you should create a logging interface or a facade and provide a way of logging to different sources.

    This is a complete solution in Kotlin:

    import org.powermock.modules.junit4.PowerMockRunner
    import org.powermock.api.mockito.PowerMockito
    import org.powermock.core.classloader.annotations.PrepareForTest
    
    /**
     * Logger Unit tests
     */
    @RunWith(PowerMockRunner::class)
    @PrepareForTest(Log::class)
    class McLogTest {
    
        @Before
        fun beforeTest() {
            PowerMockito.mockStatic(Log::class.java)
            Mockito.`when`(Log.i(any(), any())).then {
                println(it.arguments[1] as String)
                1
            }
        }
    
        @Test
        fun logInfo() {
            Log.i("TAG1,", "This is a samle info log content -> 123")
        }
    }
    

    remember to add dependencies in gradle:

    dependencies {
        testImplementation "junit:junit:4.12"
        testImplementation "org.mockito:mockito-core:2.15.0"
        testImplementation "io.kotlintest:kotlintest:2.0.7"
        testImplementation 'org.powermock:powermock-module-junit4-rule:2.0.0-beta.5'
        testImplementation 'org.powermock:powermock-core:2.0.0-beta.5'
        testImplementation 'org.powermock:powermock-module-junit4:2.0.0-beta.5'
        testImplementation 'org.powermock:powermock-api-mockito2:2.0.0-beta.5'
    }
    

    To mock Log.println method use:

    Mockito.`when`(Log.println(anyInt(), any(), any())).then {
        println(it.arguments[2] as String)
        1
    }
    

提交回复
热议问题