简体   繁体   中英

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

I'm pretty new to unit testing. I've been given the task of testing this code. I understand that I have to use assertEquals to check if for example if RegionData.Key.DEV returns VZCRegion.Development. Any help would be appreciated.

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
    }

In general, a Testclass in Kotlin looks like:

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

For each class u wish to test, create another Test class. Now, for each usecase, create a method which shall test this behavior. In my case, I wanted to test if a new Node has no neighbours.

Make sure to implement the junit enviroment in your build.gradle

Hope you can apply this construct to your problem

First of all welcome to stackoverflow!

To get started with unit testing I will recommend you to read about them in general, good starting point, another stackoverflow answer

Now back to your test. You should create a test class under your test directory , not part of your main package.

The class could look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM