面试题答案
一键面试定义注解
- 在Kotlin代码中创建一个注解类,使用
annotation
关键字定义。例如:
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class CustomIntegrationTest(val configFileName: String)
这里使用@Retention(AnnotationRetention.RUNTIME)
确保注解在运行时可用,@Target(AnnotationTarget.FUNCTION)
表示该注解用于函数。configFileName
是注解的参数,用于指定测试配置文件的名称。
解析注解
- 创建一个自定义的测试运行器(
TestRunner
)。继承AndroidJUnitRunner
或其他适合的基础测试运行器类。
class CustomTestRunner : AndroidJUnitRunner() {
override fun createTest(testClass: Class<*>, name: String): Test? {
val method = testClass.getMethod(name)
if (method.isAnnotationPresent(CustomIntegrationTest::class.java)) {
// 这里解析注解并做相应处理
val annotation = method.getAnnotation(CustomIntegrationTest::class.java)
val configFileName = annotation.configFileName
// 后续可以根据configFileName进行配置文件加载等操作
}
return super.createTest(testClass, name)
}
}
- 在
build.gradle
文件中指定使用自定义的测试运行器:
android {
defaultConfig {
testInstrumentationRunner "com.example.CustomTestRunner"
}
}
动态加载测试配置文件
- 在解析注解获取到配置文件名后,使用Android的资源读取机制或文件读取机制加载配置文件。例如,假设配置文件是JSON格式:
fun loadConfigFile(configFileName: String): String? {
try {
val inputStream = applicationContext.assets.open(configFileName)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
return String(buffer)
} catch (e: IOException) {
e.printStackTrace()
return null
}
}
- 加载完配置文件内容后,可以根据配置文件的格式进行解析。如果是JSON,可以使用Gson库:
import com.google.gson.Gson
data class TestConfig(val someParam: String)
fun parseConfig(configContent: String): TestConfig? {
return try {
Gson().fromJson(configContent, TestConfig::class.java)
} catch (e: JsonSyntaxException) {
e.printStackTrace()
null
}
}
- 将解析后的配置应用到测试用例中,例如在测试方法执行前设置一些测试环境参数:
class ExampleInstrumentedTest {
@CustomIntegrationTest("test_config.json")
@Test
fun someTest() {
val method = javaClass.getMethod("someTest")
val annotation = method.getAnnotation(CustomIntegrationTest::class.java)
val configFileName = annotation.configFileName
val configContent = loadConfigFile(configFileName)
val config = parseConfig(configContent)
// 使用config进行测试环境设置等操作
assertEquals(4, 2 + 2)
}
}