跳至主要内容

PropertyDescriptorTester

在 ChatGPT 中打开
23.06 实验性
Java API

PropertyDescriptorTester 在 webforJ 中简化了集成到您的应用程序中的 第三方网页组件 的测试。它验证使用 PropertyDescriptor 定义的属性是否正确链接到其获取器和设置器方法,并确保默认行为的一致处理。此工具非常适合验证第三方组件暴露的属性的功能,而无需重复测试逻辑。

实验性功能
此功能为实验性,未来版本可能会改变或删除。

概述

在使用第三方网页组件时,确保属性按预期行为至关重要。PropertyDescriptorTester 通过验证属性来自动化此过程:

  • 是否正确映射到其获取器和设置器方法。
  • 是否维护预期的默认值和自定义行为。
  • 是否避免常见集成问题,例如属性名称不匹配或默认值不一致。

该工具支持更复杂用例的注释,例如排除无关属性或定义自定义获取器和设置器方法,使其成为集成测试的多功能选择。

PropertyDescriptorTester 的工作原理

测试过程涉及多个自动化步骤:

  1. 类扫描PropertyDescriptorScanner 识别组件类中的所有 PropertyDescriptor 字段,自动排除带有 @PropertyExclude 注释的字段。

  2. 方法解析: 标准获取器和设置器方法基于命名约定(get<PropertyName>/set<PropertyName>)进行检测。对于非标准实现,注释如 @PropertyMethods 指定自定义方法名称或目标类。

  3. 验证: 使用设置器方法分配默认值,使用获取器方法检索并进行比较以确保正确性。任何不匹配都会触发 AssertionError,突出特定问题。

  4. 错误报告: 测试工具提供详细反馈,针对任何验证失败,例如缺失方法、不一致的默认值或属性配置错误。

使用 PropertyDescriptorTester 编写测试

以下是演示 AppLayout 组件基本属性验证的示例:

示例:基本验证

MyComponent.java
public class MyComponent extends ElementCompositeContainer {
private final PropertyDescriptor<Boolean> drawerOpened =
PropertyDescriptor.property("drawerOpened", false);
private final PropertyDescriptor<String> headerTitle =
PropertyDescriptor.property("headerTitle", "Default Title");

// setters and getters
}

测试用例

MyComponentTest.java
import com.webforj.component.element.PropertyDescriptorTester;
import org.junit.jupiter.api.Test;

class MyComponentTest {

MyComponent component = new MyComponent();

@Test
void validateProperties() {
try {
PropertyDescriptorTester.run(MyComponent.class, component);
} catch (Exception e) {
fail("PropertyDescriptor 测试失败: " + e.getMessage());
}
}
}

此测试自动验证:

  • drawerOpened 是否具有有效的获取器和设置器方法。
  • headerTitle 是否默认值为 "Default Title"

使用注释的高级用例

对于更复杂的场景,PropertyDescriptorTester 支持注释以自定义或排除测试属性。

使用 @PropertyExclude 排除属性

排除依赖外部系统或与测试无关的属性。例如:

@PropertyExclude
private final PropertyDescriptor<String> excludedProperty =
PropertyDescriptor.property("excludedProperty", "Excluded");

使用 @PropertyMethods 自定义方法

当默认命名约定不适用时,定义自定义获取器、设置器或目标类:

@PropertyMethods(getter = "retrieveValue", setter = "updateValue", target = InnerClass.class)
private final PropertyDescriptor<String> customProperty =
PropertyDescriptor.property("customProperty", "Default Value");