1

如何在 kotlin 中测试执行如下 readline 的代码:

import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.*
import java.io.*
fun foo() {
    val string="a b\nc d"
    var bais: ByteArrayInputStream=string.byteInputStream()
    val bis=BufferedInputStream(bais)
    //var l=bis.readLine() // no readline!
    // program uses just readline()
    var br: BufferedReader =BufferedReader(InputStreamReader(bais))
    var l=br.readLine()
    println(l) // works file
    val si=System.`in`
    println("System.`in` is ${si::class.simpleName}") // says it's a BufferedInputStream
}
fun main() {
    foo()
}
@TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class T1KtTestCase {
    @Test fun testFoo() {
        // ?
    }
}
4

1 回答 1

0

您可以将inputStreamoutputStream作为参数添加到您的函数foo

fun foo(inputStream: InputStream, outputStream: OutputStream) {
    val name = BufferedReader(InputStreamReader(inputStream)).readLine()
    PrintStream(outputStream).println("Hello, ${name.trim()}!")
}

fun main() {
    foo(System.`in`, System.out)
}

然后您可以foo按如下方式测试您的功能:

class Test {

    @Test
    fun testFoo() {
        val inputStream = "username".byteInputStream()
        val outputStream = ByteArrayOutputStream()
        foo(inputStream, outputStream)
        assertEquals(String(outputStream.toByteArray()), "Hello, username!\n")
    }

}
于 2020-05-03T21:42:14.637 回答