1

I'm working on an Android app written in Kotlin. I would like to use Log.* to see the output of some very simple logic in a unit test, rendered as string. I'm using mockk as suggestested in this other question.

I don't get any errors, the test works fine; however, not even a single line is printed in the Logcat of Android Studio. I checked filters and current device with no avail.

Here is my simplified code:

// UnitTest.kt
class MyUnitTest {
  @Before
  fun setup() {
    mockkStatic(Log::class)
    every { Log.d(any(), any()) } returns 0
  }

  @Test
  fun do_test() {
    // ... some logic
    Log.d("TEST_TAG", "Test string")
  }
}

I also tried to:

  • put the Log in a function marked as @JvmStatic into a companion object
  • adding the following to app level build.gradle as suggested here (though unrecommended)
testOptions {
  unitTests.returnDefaultValues = true
} 
  • get rid of everything and use a kotlin implementation of the main answer. Something like this:
// app/src/test/android/util/MyLog.kt
package android.util

class MyLog {
  companion object {
    @JvmStatic
    fun d(tag: String, msg: String): Int {
      println("DEBUG: $tag: $msg")
      return 0
    }
}

Unfortunately none of these worked (with any of the Log levels).

I don't have great experience in writing tests, am I missing something?

Edit (about solution):

I was targeting Logcat, which is wrong, because unit tests run on a local machine.

Onik
  • 19,396
  • 14
  • 68
  • 91
Fiordarancio
  • 63
  • 1
  • 9

1 Answers1

1

You need to use println() for logging in unit tests.

Logcat shows messages coming from a device. As unit tests are running on your local machine, it is physically impossible to see messages. println() prints messages to the test "console".

Onik
  • 19,396
  • 14
  • 68
  • 91
  • This is what I do when using `MyLog.d()` instead of `Log.d` but I can't still see anything in my Logcat :( – Fiordarancio Mar 02 '23 at 12:01
  • 1
    Logcat shows messages coming from a device. As unit tests are running on your local machine, it is physically impossible to see messages. `println()` prints messages to the test "console" – Onik Mar 02 '23 at 12:23
  • 1
    Thank you for your clarification! I was sure I was missing some simple technical detail – Fiordarancio Mar 02 '23 at 13:11