Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 重写单元测试上的类_Android_Unit Testing_Kotlin - Fatal编程技术网

Android 重写单元测试上的类

Android 重写单元测试上的类,android,unit-testing,kotlin,Android,Unit Testing,Kotlin,我想在我的Android项目中对我的代码进行一些测试。我有一个类(a)提供对数据库的访问,另一个类(B)使用它。我为B创建了一个测试类(BTest),但我需要重写类a,这样当BTest从B调用方法(将从a调用方法)时,返回特定的值,而不是实际访问我的数据库。可以进行单元测试吗 object A{ fun getValue(): String{ return DB.getValue(); //here I access my database to retrieve the

我想在我的Android项目中对我的代码进行一些测试。我有一个类(a)提供对数据库的访问,另一个类(B)使用它。我为B创建了一个测试类(BTest),但我需要重写类a,这样当BTest从B调用方法(将从a调用方法)时,返回特定的值,而不是实际访问我的数据库。可以进行单元测试吗

object A{
    fun getValue(): String{
        return DB.getValue(); //here I access my database to retrieve the value
    }
}

object B{
    fun doStuff(): String{
        val value = A.INSTANCE.getValue()
        //process the value
        return processedValue
    }
}

class BTest{
    @Test
    fun testDoStuff(){
        Assert.isSame(B.INSTANCE.doStuff(), “result”) //at the moment this is accessing the database.
    }
}
因此,在我的测试文件夹中有一个新的a类,当testDoStuff()中的B调用a.INSTANCE.getValue()时,我可以执行其他操作,而不是实际访问数据库


谢谢

你应该做依赖注入,最简单的方法是将A传递给B的构造函数,而不是B直接访问A。这样,在测试中你可以传递A的任何子类。(另外,
对象类
不是有效语法,但我想这是一个疏忽)依赖注入可以是一个选项,谢谢。我想知道,对于这种情况,测试api是否会有覆盖的内容。(固定对象类-很抱歉,我背起kotlin sintax来举了个例子):)