簡體   English   中英

我將如何 go 關於在 Kotlin 中對這個 function 進行單元測試?

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

我對單元測試很陌生。 我被賦予了測試這段代碼的任務。 我知道我必須使用 assertEquals 來檢查 RegionData.Key.DEV 是否返回 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 中的 Testclass 如下所示:

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 環境

希望您可以將此構造應用於您的問題

首先歡迎來到stackoverflow!

要開始進行單元測試,我建議您大致閱讀它們,好的起點,另一個 stackoverflow 答案

現在回到你的測試。 您應該在您的測試目錄下創建一個測試 class,而不是您的主要 package 的一部分。

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)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM