Search code examples
unit-testingkotlinjunit4

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
    }

Solution

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