【问题标题】:How would I go about unit testing this function in Kotlin?我将如何在 Kotlin 中对这个函数进行单元测试?
【发布时间】:2019-11-06 19:46:11
【问题描述】:

我对单元测试很陌生。我被赋予了测试这段代码的任务。我知道我必须使用 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
    }

【问题讨论】:

    标签: unit-testing kotlin junit4


    【解决方案1】:

    首先欢迎来到stackoverflow!

    要开始进行单元测试,我建议您大致了解它们,良好的起点,another stackoverflow answer

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

    类可能看起来像

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

    【讨论】:

      【解决方案2】:

      一般来说,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)
          }
      }
      

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

      确保在你的 build.gradle 中实现 junit 环境

      希望您可以将此构造应用于您的问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 2019-04-15
        相关资源
        最近更新 更多