我将如何在 Kotlin 中对这个函数进行单元测试?

How would I go about unit testing this function in Kotlin?

我对单元测试还很陌生。我被赋予了测试这段代码的任务。我知道我必须使用 assertEquals 来检查是否,例如 RegionData.Key.DEV returns VZCRegion.Development。 任何帮助,将不胜感激。

fun fromCakeSliceRegion(cakeSliceIndex: RegionData.Key): VZCRegion {

    return when (cakeSliceIndex) {
        RegionData.Key.DEV -> VZCRegion.Development
        RegionData.Key.EU_TEST -> VZCRegion.EuropeTest
        RegionData.Key.US_TEST -> VZCRegion.UnitedStatesTest
        RegionData.Key.US_STAGING -> VZCRegion.UnitedStatesStage
        RegionData.Key.EU_STAGING -> VZCRegion.EuropeStage
        RegionData.Key.LOCAL, RegionData.Key.EU_LIVE -> VZCRegion.Europe
        RegionData.Key.AP_LIVE, RegionData.Key.US_LIVE -> VZCRegion.UnitedStates
        RegionData.Key.PERFORMANCE, RegionData.Key.PERFORMANCE -> VZCRegion.Performance
    }

一般来说,Kotlin 中的测试class 看起来像:

import org.junit.Assert.assertTrue
class NodeTest {

    @Test
    fun neighbourCountValidation(){
        //This is a snipped of my test class, apply your tests here.
        val testNode = Node(Point(2,0))
        assertTrue(testNode.neighbourCount()==0)
    }
}

对于您希望测试的每个 class,创建另一个测试 class。现在,对于每个用例,创建一个测试此行为的方法。就我而言,我想测试一个新节点是否没有邻居。

确保在您的 build.gradle

中实施 junit 环境

希望您能将此构造应用到您的问题中

首先欢迎来到Whosebug!

要开始单元测试,我会建议您阅读有关它们的一般内容,这是一个很好的起点,another Whosebug answer

现在回到你的测试。您应该在 测试目录 下创建一个测试 class,而不是主包的一部分。

class 可能看起来像

import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test

class TestCakeSlice {
    @Before
    fun setUp() {
        // this will run before every test
        // usually used for common setup between tests
    }

    @After
    fun tearDown() {
        // this will run after every test
        // usually reset states, and cleanup
    }

    @Test
    fun testSlideDev_returnsDevelopment() {
        val result = fromCakeSliceRegion(RegionData.Key.DEV)

        Assert.assertEquals(result, VZCRegion.Development)
    }

    @Test
    fun `fun fact you can write your unit tests like this which is easier to read`() {
        val result = fromCakeSliceRegion(RegionData.Key.DEV)

        Assert.assertEquals(result, VZCRegion.Development)
    }
}