【问题标题】:How to write a unit test for a function with specific type in kotlin如何在 kotlin 中为具有特定类型的函数编写单元测试
【发布时间】:2021-09-21 23:48:16
【问题描述】:

鉴于我的功能如下:

fun myFunction(Id: String): returnType {
        val entity = repo.findById(Id)
        // this anotherProperty has a type: List<Type1>, where Type1 is a enum class
        val anotherProperty = entity.anotherProperty.toConvert(). 
        return anotherComponent.findByIdAndProperty(Id, anotherProperty)
}

fun List<Type1>.toConvert(): Type1 {
        return when {
            contains(Type1.enum1) -> {
                Type1.enum1
            }
            contains(Type1.enum2) -> {
                Type1.enum2
            }
            else -> {
                Type1.enum3
            }
        }
    }

我想为这两个函数写三个单元测试(因为我有toConvert函数的三个条件)。更像是当val anotherProperty 包含某些内容时,我应该调用anotherComponent.findByIdAndProperty(Id, anotherProperty)

但我只是找不到在我的测试中调用此toConvert 的位置。

【问题讨论】:

  • toConvert 是一个extension functions,带有一个List&lt;Type1&gt; 接收器。您能否通过示例测试和示例列表更新您的问题?

标签: java unit-testing kotlin testing


【解决方案1】:

toConvert() 函数的基本测试如下所示:

@Test fun toConvertReturnsEnum1() {
  val inputList: List<Type1> = listOf(Type1.enum1, Type1.enum2, Type1.enum3)
  val convertedValue: Type1 = inputList.toConvert()
  assertEquals(Type1.enum1, convertedValue)
}

@Test fun toConvertReturnsEnum2() {
  val inputList: List<Type1> = listOf(Type1.enum2, Type1.enum3)
  val convertedValue: Type1 = inputList.toConvert()
  assertEquals(Type1.enum2, convertedValue)
}

等等

然后测试 myFunction 应该忽略 toConvert 函数的存在 - 它们应该像一个黑匣子,所以你知道函数的输入是什么 (Id),你只需检查 myFunction("testedId") 的结果 if这是你所期望的。 换句话说:以忽略toConvert 函数的存在的方式为myFunction 创建测试,您可以想象您将所有代码从toConvert 直接复制到myFunction,因此您需要在此测试整个逻辑通过提供输入并检查其输出来发挥作用。

您还可以考虑是否真的需要将toConvert 函数添加到List&lt;Type1&gt; - 如果您只需要myFunction,那么最好在您所在的类/对象中创建私有方法拥有myFunction,因此无法在其外部访问。那么可能更清楚的是,您不应该对 toConvert 函数进行任何测试,而应该只向 myFunction 提供所有必要的输入,这样它就会在后台调用 toConvert 的所有可能情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多