如何在测试中使用 Location 对象?
How to use Location objects in tests?
我正在尝试编写测试来测试一些操纵 Location 对象的代码。
使用 @Before
JUnit 注释,我想初始化一个 Location 实例,这样:
@Before
fun init_service() {
location = Location(LocationManager.GPS_PROVIDER)
System.out.println("init $location")
}
执行我的测试时,输出不是很令人满意,打印:init null
。
知道这段代码在经典上下文中工作,是否有一种特殊的方法可以在测试上下文中初始化对象实例?
要测试 Android 特定代码,您需要隐藏 SDK classes。您可以使用 Robolectric。只需将依赖项添加到 build.gradle
并用 @RunWith(RobolectricTestRunner::class)
注释您的测试 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)
}
}
我正在尝试编写测试来测试一些操纵 Location 对象的代码。
使用 @Before
JUnit 注释,我想初始化一个 Location 实例,这样:
@Before
fun init_service() {
location = Location(LocationManager.GPS_PROVIDER)
System.out.println("init $location")
}
执行我的测试时,输出不是很令人满意,打印:init null
。
知道这段代码在经典上下文中工作,是否有一种特殊的方法可以在测试上下文中初始化对象实例?
要测试 Android 特定代码,您需要隐藏 SDK classes。您可以使用 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)
}
}