SharkLogTest.kt
TLDR
This file contains a test class SharkLogTest
that tests the logging functionality of the SharkLog
class.
Methods
logging works when logger is set
This test method verifies that the debug logging works correctly when a logger is set. It creates a StreamLogger
and sets it as the logger for SharkLog
. Then it logs a debug message using a lambda expression and asserts that the output stream contains the expected message.
logging with exception works when logger is set
This test method verifies that logging with an exception works correctly when a logger is set. It creates a StreamLogger
and sets it as the logger for SharkLog
. Then it logs an exception and a debug message using a lambda expression and asserts that the output stream contains the expected message.
logging is no-op without logger and string is ignored
This test method verifies that logging is a no-op when no logger is set and the string is ignored. It sets the SharkLog
logger to null and attempts to log a message and an exception. This test is primarily to ensure that no exceptions are thrown when logging is performed without a logger.
Classes
SharkLogTest
This class is a test class that tests the logging functionality of the SharkLog
class. It contains three test methods described above.
package shark
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import shark.SharkLog.Logger
import java.io.ByteArrayOutputStream
import java.io.PrintStream
class SharkLogTest {
private class StreamLogger(private val stream: PrintStream) : Logger {
override fun d(message: String) = stream.print(message)
override fun d(
throwable: Throwable,
message: String
) = stream.print("$message ${throwable.message}")
}
@Test fun `logging works when logger is set`() {
val outputStream = ByteArrayOutputStream()
SharkLog.logger = StreamLogger(PrintStream(outputStream))
// Test debug logging
SharkLog.d { "Test debug" }
assertThat(outputStream.toString()).isEqualTo("Test debug")
}
@Test fun `logging with exception works when logger is set`() {
val outputStream = ByteArrayOutputStream()
SharkLog.logger = StreamLogger(PrintStream(outputStream))
// Test error logging
SharkLog.d(Exception("Test exception")) { "Test error" }
assertThat(outputStream.toString()).isEqualTo("Test error Test exception")
}
@Test fun `logging is no-op without logger and string is ignored`() {
SharkLog.logger = null
// Logging message will throw an exception when attempting to use it
// But since it's in lambda string will not be accessed
SharkLog.d { "".substring(1) }
SharkLog.d(Exception("Test exception")) { "".substring(1) }
}
}