Unit testing 如何在Kotlin中测试tailrec功能?

Unit testing 如何在Kotlin中测试tailrec功能?,unit-testing,testing,recursion,kotlin,tail-recursion,Unit Testing,Testing,Recursion,Kotlin,Tail Recursion,我正在尝试测试以下tailrec功能: private tailrec fun findFixPoint(eps: Double = 5.0, x: Double = 1.0): Double = if (abs(x - cos(x)) < eps) x else findFixPoint(cos(x)) @Test fun testNewFeatures(){ TestCase.assertEquals(0.7390851332151611, findFixPoint(

我正在尝试测试以下tailrec功能:

    private tailrec fun findFixPoint(eps: Double = 5.0, x: Double = 1.0): Double = if (abs(x - cos(x)) < eps) x else findFixPoint(cos(x))
@Test
fun testNewFeatures(){
    TestCase.assertEquals(0.7390851332151611, findFixPoint())
}
@Test
fun testNewFeatures(){

    TestCase.assertEquals(10000000000.0, testStackOverFlow(1.0))
    TestCase.assertEquals(10000000000.0, testNOTStackOverFlow(1.0))
}
固定点是
0.7390851332151611
,但是
assertEquals
返回我
1.0
,因为
实际值
我可以扣除函数只启动一次而没有递归

关于如何测试
tailrec
功能的任何建议

希望有人能帮我。提前谢谢大家


编辑

这篇文章的真正目的是测试tailrec函数,以避免出现
stackoverflower错误
,因此,我将在这里发布两个简单的测试,但是
sa1nt
'的答案对于我的问题是正确的,
Benoit
的提示对于简化tailrec测试非常有用

因此,以下用于测试StackOverflowerError的函数如下所示:

无法避免

private fun testStackOverFlow(num : Double): Double = if (num == 10000000000.0) num else testStackOverFlow(num+1)
避免

private tailrec fun testNOTStackOverFlow(num : Double): Double = if (num == 10000000000.0) num else testNOTStackOverFlow(num+1)
测试功能:

    private tailrec fun findFixPoint(eps: Double = 5.0, x: Double = 1.0): Double = if (abs(x - cos(x)) < eps) x else findFixPoint(cos(x))
@Test
fun testNewFeatures(){
    TestCase.assertEquals(0.7390851332151611, findFixPoint())
}
@Test
fun testNewFeatures(){

    TestCase.assertEquals(10000000000.0, testStackOverFlow(1.0))
    TestCase.assertEquals(10000000000.0, testNOTStackOverFlow(1.0))
}
谢谢大家的回答。祝你度过愉快的一天。

对于这种方法,似乎是最合适的。基本上,您在不了解内部细节的情况下测试该方法。您只需检查结果对于给定输入是否正确,即方法的作用。这就是你所做的。但是没有必要检查该方法是如何得出这个结果的

现在假设您完全重写了方法,使用迭代而不是递归:您不需要重写测试,它们都保持有效。

TLDR
  • 将您的功能更改为:
  • 细节
  • 在递归调用中显式提供这两个参数。否则,
    cos(x)
    将用于
    eps
    ,因为它是第一个参数:
    private tailrec fun find expoint(eps:Double=5.0,x:Double=1.0):Double=if(abs(x-cos(x))

  • 在测试中,您像这样调用函数
    findExpoint()
    ,因此使用默认参数值。因此,对于
    eps=5.0
    x=1.0
    的条件
    if(abs(x-cos(x))
    将在进入函数后立即返回
    x


  • “否则5.0的默认值将在递归调用中使用”不完全正确
    cos(x)
    将用于
    eps
    ,而
    x
    @Alexey的默认1.0将使用您的输入更新答案。谢谢我将文本更改为更简单的文本,为了使用tailrec fun或normal fun测试stackoverflow错误,我将把它添加到问题中。谢谢你的关注