如何从 java 测试代码访问内部属性
how to access internal properties from java test code
我有一些 class,其中 属性 标记为内部。
然后我尝试从 java 中的测试代码设置 属性。
我怎样才能访问这些属性?测试代码和class代码在同一个包中。
示例:
class MainActivity : AppCompatActivity() {
interal var someProperty = "test"
}
测试代码:
@Test
public void firstStartTest() {
val activity = MainActivity()
activity.setSomeProperty("something") //does not compile
}
Android Studio 建议 activity.setSomeProperty$production_sources_for_module_app();
但这也无法编译。
两个 classes(MainActivity 和测试 class)必须在一个模块中。这是一个模块定义:
More specifically, a module is a set of Kotlin files compiled together:
- an IntelliJ IDEA module;
- a Maven or Gradle project;
- a set of files
compiled with one invocation of the Ant task.
https://kotlinlang.org/docs/reference/visibility-modifiers.html
也就是说,检查你的项目结构。
有两种方法可以做到这一点:
- 制作属性
protected
。请注意 Java 和 Kotlin 如何以不同方式对待 protected
。在 Java 中,同一包中的其他 class 可能会访问 protected
成员。因此,您的测试 class(在 Java 中)可以访问它。
- 通过丑陋的名字访问 属性。它应该有点像
activity.setSomeProperty$production_...
。使用自动完成功能。来自 the documentation:
Members of internal classes go through name mangling, to make it
harder to accidentally use them from Java and to allow overloading for
members with the same signature that don't see each other according to
Kotlin rules;
添加@JvmField 注解。
它将变量视为 java protected
我有一些 class,其中 属性 标记为内部。 然后我尝试从 java 中的测试代码设置 属性。 我怎样才能访问这些属性?测试代码和class代码在同一个包中。
示例:
class MainActivity : AppCompatActivity() {
interal var someProperty = "test"
}
测试代码:
@Test
public void firstStartTest() {
val activity = MainActivity()
activity.setSomeProperty("something") //does not compile
}
Android Studio 建议 activity.setSomeProperty$production_sources_for_module_app(); 但这也无法编译。
两个 classes(MainActivity 和测试 class)必须在一个模块中。这是一个模块定义:
More specifically, a module is a set of Kotlin files compiled together:
- an IntelliJ IDEA module;
- a Maven or Gradle project;
- a set of files compiled with one invocation of the Ant task.
https://kotlinlang.org/docs/reference/visibility-modifiers.html
也就是说,检查你的项目结构。
有两种方法可以做到这一点:
- 制作属性
protected
。请注意 Java 和 Kotlin 如何以不同方式对待protected
。在 Java 中,同一包中的其他 class 可能会访问protected
成员。因此,您的测试 class(在 Java 中)可以访问它。 - 通过丑陋的名字访问 属性。它应该有点像
activity.setSomeProperty$production_...
。使用自动完成功能。来自 the documentation:Members of internal classes go through name mangling, to make it harder to accidentally use them from Java and to allow overloading for members with the same signature that don't see each other according to Kotlin rules;
添加@JvmField 注解。 它将变量视为 java protected