测试类内部的扩展功能 [英] Testing extension functions inside classes

查看:119
本文介绍了测试类内部的扩展功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们要测试某个类型的扩展功能,则可以创建此类型的实例,调用该功能并检查返回的值.但是,如何测试在类内部定义的扩展功能呢?

If we want to test an extension function on a type, we can create an instance of this type, call the function and check the returned value. But what about testing extension functions defined inside classes?

abstract class AbstractClass<T> {
    fun doStuff(): T = "Hello".foo()

    abstract fun String.foo(): T
}

class SubClass1: AbstractClass<Int>() {
    override fun String.foo(): Int = 1
}

class SubClass2: AbstractClass<Boolean>() {
    override fun String.foo(): Boolean = true
}

我们如何在类SubClass1SubClass2中测试方法foo()的逻辑?甚至有可能吗?

How do we test the logic of the methods foo() in classes SubClass1 and SubClass2? Is it even possible?

我知道我可以更改设计以对其进行测试.我想到了两种可能性:

I know I can change the design to test it. Two possibilities have occurred to me:

  1. 不使用扩展功能. ¯\ _(ツ)_/¯

  1. Don't use extension functions. ¯\_(ツ)_/¯

abstract class AbstractClass<T> {
    fun doStuff(): T = foo("Hello")

    abstract fun foo(string: String): T
}

class SubClass1: AbstractClass<Int>() {
    override fun foo(string: String): Int = 1
}

然后我们可以创建一个对象SubClass1,调用foo()并检查返回的值.

Then we can create an object SubClass1, call foo() and check the returned value.

创建具有internal可见性的其他扩展功能只是为了测试逻辑.

Create additional extension functions with internal visibility just to test the logic.

class SubClass1: AbstractClass<Int>() {
    override fun String.foo(): Int = internalFoo()
}

internal fun String.internalFoo(): Int = 1

然后我们可以创建一个对象String,调用internalFoo()并检查返回的值.但是,我不喜欢这种解决方案,因为我们可以更改override fun String.foo(): Int的主体,并且测试会通过.

Then we can create an object String, call internalFoo() and check the returned value. However, I don't like this solution because we could change the body of override fun String.foo(): Int and our test would pass.

那么,是否可以在类内部测试扩展功能?如果没有,您将如何更改设计以测试其逻辑?

So, is it possible to test extension functions inside classes? If not, how would you change your design in order to test their logic?

推荐答案

由于应该从客户的角度编写测试,所以我不确定这将是有效的测试.但是我确实提出了一种测试方法.

Since tests should be written from the client's perspective, I'm not sure it would be a valid test. But I did come up with one way to test it.

@Test
fun `test extension function`() {
    var int = 0

    SubClass1().apply {
        int = "blah".foo()
    }

    assertThat(int, `is`(1))
}

这篇关于测试类内部的扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆