Android Junit 测试用例出现 stackoverflow 错误

Android Junit testcase getting stackoverflow error

我曾尝试为某些出现 Whosebug 错误的模型 class 编写测试用例,我发现这是递归调用的问题,但我不确定是否属于这种情况?任何人都可以帮助我编写测试用例递归调用。谁能帮我解决下面的示例代码,我该如何解决?

注意:我在分配数据函数的 getComponentsData() 上遇到 Whosebug 错误。

class ComponentTest {

lateinit var classUnderTest: ComponentTest

@Before
fun setUp() {
    classUnderTest = ComponentTest()
}

@Test
fun `test to convert Component with one set Component`() {
    val component = getComponentsData()
    val result = classUnderTest.convert(component)
    testComponent(result)
}

private fun testComponent(result: ContentComponentBO?) {
    Assert.assertNotNull(result)
    Assert.assertEquals("taggingGroup",
                        result?.taggingGroup)
    Assert.assertEquals("componentType",
                        result?.componentType)
    testCollection(result?.collection?.first())
}

private fun getComponentsData(): Component {
    return Component().apply {
        taggingGroup = "taggingGroup"
        componentType = "componentType"
        collection = listOf(getCollectionData())
        name = "name"
        headerText = "headerText"
        pageHeader = "pageHeader"
        iroaButton = getCollectionData()
        isOpenInOverlay = false
        overlayHeader = "overlayHeader"
    }
}

private fun getCollectionData(): Collection {
    return Collection().apply {
        defaultGroup = false
        groupName = "groupName"
        collection = listOf(getCollectionData())
        isOpenInOverlay = true
        image2ShoppingCategory = "image2ShoppingCategory"
        components = listOf(getComponentsData())
        categoryName = "categoryName"
    }
}

}

让我们尝试描述部分调用堆栈:

`test to convert Component with one set Component` calls  getComponentsData()

getComponentsData() calls getCollectionData() to set iroaButton

这是有趣的部分,您有两个潜在的问题。我说有潜力是因为我可以部分访问代码,但在以下情况下您似乎遇到了一个问题:

getCollectionData() calls getCollectionData() to set collection
then getCollectionData() calls getCollectionData() to set collection
then getCollectionData() calls getCollectionData() to set collection
then getCollectionData() calls getCollectionData() to set collection
then getCollectionData() calls getCollectionData() to set collection

然后当

getCollectionData() calls getComponentsData() to set components  
getComponentsData() calls getCollectionData() to set iroaButton
then getCollectionData() calls getComponentsData() to set components  
then getComponentsData() calls getCollectionData() to set iroaButton
then getCollectionData() calls getComponentsData() to set components  
then getComponentsData() calls getCollectionData() to set iroaButton

您的代码在 recursion 方面存在问题。

Recursion means "defining a problem in terms of itself".

In other words,我们可以将递归的思想提炼成两个简单的规则:

  1. 每个递归调用都应该针对同一问题的较小实例,即较小的子问题。
  2. 递归调用最终必须达到基本情况,无需进一步递归即可解决。

您的代码的问题是没有基本情况。方法 getCollectionData() 调用 getCollectionData() 并卡住,直到堆栈溢出,因为没有任何东西可以让您的代码停止。