【问题标题】:How to test code that uses readline (System.`in`) in kotlin?如何在 kotlin 中测试使用 readline (System.`in`) 的代码?
【发布时间】:2020-05-03 16:55:48
【问题描述】:

如何在 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() {
        // ?
    }
}

【问题讨论】:

  • 您正在使用 java 框架,在 System 方法的 kotlin 测试中与 java 没有区别。检查这个stackoverflow.com/questions/1119385/…
  • 是的。看起来我很兴奋,因为我需要模拟 readLine()

标签: kotlin intellij-idea junit5 system.in junit-jupiter


【解决方案1】:

您可以将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")
    }

}

【讨论】:

  • 是的,但是如何测试一段包含 readLine() 并使用 system.in 的代码?
  • 我已经编辑了我的答案,现在我使用readLine() 方法来读取输入。你不能测试System.in 或者太难了。问问自己你想测试什么。在我的示例中,最好有单独的 fun sayHello(name: String) { return "Hello $name" } 并仅测试该功能。这就是单元测试的重点,您应该测试程序的一小部分。
猜你喜欢
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多