[英]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.