Why Log.d() print nothing when running Android Local Unit Test?
I suggest you to use interface:
interface PlatformLog {
fun e(tag: String, msg: String, throwable: Throwable?=null)
fun i(tag: String, msg: String)
}
create an interface for example:
in unit tests:
class SystemPlatformLog : PlatformLog {
override fun i(tag: String, msg: String) {
println("$tag : $msg")
}
override fun e(tag: String, msg: String, throwable: Throwable?) {
println("$tag : $msg")
}
}
In android
class AndroidPlatformLog : PlatformLog {
override fun i(tag: String, msg: String) {
Log.i(tag, msg)
}
override fun e(tag: String, msg: String, throwable: Throwable?) {
Log.e(tag, msg, throwable)
}
}
Usage: In android
private val log: PlatformLog = AndroidPlatformLog()
public override fun onCreate(savedInstanceState: Bundle?) {
log.i(TAG, "onCreate $savedInstanceState")
}
In tests
private val log: PlatformLog = SystemPlatformLog()
@Test
fun `should log in System`() {
log.i(TAG, "called from tests")
}
OR with dagger2 in two cases:
@Inject lateinit var log: PlatformLog
public override fun onCreate(savedInstanceState: Bundle?) {
log.i(TAG, "onCreate $savedInstanceState")
}
in tests
class MyTest{
@Inject lateinit var log: PlatformLog
@Before
fun setUp() {
val component = DaggerTestComponent.builder().testModule(TestModule()).build()
component.inject(this)
}
@Test
fun `should log in System`() {
log.i(TAG, "called from tests")
}
@Module
open class TestModule {
@Provides
@Singleton
open fun providePlatformLog(): PlatformLog {
return SystemPlatformLog()
}
}
@Singleton
@Component(modules = [TestModule::class])
interface TestComponent {
fun inject(test: MyTest)
}
You should use standard output, System.out.println("Hello StackOverflow")
intead of Log.x()
. Then you can see the log info in the run tab.
2017/12/16 Update: If you can't see the output on the Run
tab, go to Android Monitor
tab to find the output instead.
The Jell T. answer above is right. But if you want to use Timber or Log, you can still do that.
You can search for the logs on the Logcat tab: