我正在尝试编写测试来测试一些操作Location对象的代码。使用@Before JUnit注释,我想以这种方式初始化一个Location实例:
@Before
fun init_service() {
location = Location(LocationManager.GPS_PROVIDER)
System.out.println("init $location")
}当执行我的测试时,输出不是很令人满意,打印:init null。
知道这段代码在经典上下文中工作,有没有一种特殊的方法在测试上下文中初始化对象实例?
发布于 2019-07-08 22:12:57
要测试特定于Android的代码,您需要隐藏SDK类。您可以使用Robolectric。只需向build.gradle添加依赖项并使用@RunWith(RobolectricTestRunner::class)注释您的测试类
import android.location.Location
import android.location.LocationManager
import org.junit.Before
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class Test {
@Before
fun init_service() {
val location = Location(LocationManager.GPS_PROVIDER)
location.latitude = 22.234
location.longitude = 23.394
println(location)
}
}https://stackoverflow.com/questions/56935435
复制相似问题