You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI中使用Appium获取自定义Checkbox的IsChecked属性

.NET MAUI自定义Checkbox的Appium自动化测试获取IsChecked属性问题解决

问题原因

你之前的代码无效,是因为.NET MAUI的自定义控件默认不会将自身的业务属性(比如IsChecked)暴露给自动化框架(如Appium),Appium无法直接通过GetAttribute获取未注册的自动化属性。

解决方案

1. 为自定义Checkbox实现AutomationPeer(推荐)

通过实现AutomationPeer,让自定义控件向自动化框架提供标准的交互模式(比如TogglePattern),这样Appium就能识别并获取选中状态:

首先创建自定义AutomationPeer类:

public class CustomCheckboxAutomationPeer : ViewAutomationPeer
{
    private readonly CustomCheckbox _checkbox;

    public CustomCheckboxAutomationPeer(CustomCheckbox checkbox) : base(checkbox)
    {
        _checkbox = checkbox;
    }

    public override object GetPattern(PatternInterface patternInterface)
    {
        if (patternInterface == PatternInterface.Toggle)
        {
            return new TogglePatternPeer(_checkbox);
        }
        return base.GetPattern(patternInterface);
    }

    protected override string GetClassNameCore() => nameof(CustomCheckbox);

    private class TogglePatternPeer : IToggleProvider
    {
        private readonly CustomCheckbox _checkbox;

        public TogglePatternPeer(CustomCheckbox checkbox)
        {
            _checkbox = checkbox;
        }

        public ToggleState ToggleState => _checkbox.IsChecked ? ToggleState.On : ToggleState.Off;

        public void Toggle()
        {
            _checkbox.IsChecked = !_checkbox.IsChecked;
        }
    }
}

然后在自定义Checkbox中重写OnCreateAutomationPeer方法返回该Peer:

public class CustomCheckbox : View
{
    public static readonly BindableProperty IsCheckedProperty =
        BindableProperty.Create(nameof(IsChecked), typeof(bool), typeof(CustomCheckbox), false);

    public bool IsChecked
    {
        get => (bool)GetValue(IsCheckedProperty);
        set => SetValue(IsCheckedProperty, value);
    }

    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return new CustomCheckboxAutomationPeer(this);
    }
}

之后在测试代码中通过TogglePattern获取状态:

var element = Driver.FindElement(By.Id("checkbox"));
var togglePattern = element.GetCapability<TogglePattern>(TogglePattern.Pattern);
bool isChecked = togglePattern.ToggleState == ToggleState.On;

2. 替代方案:绑定到自动化辅助属性

如果不想实现AutomationPeer,可以在XAML中将IsChecked绑定到AutomationProperties.HelpText,间接让Appium获取该值:

<local:CustomCheckbox AutomationId="checkbox"
                      AutomationProperties.HelpText="{Binding IsChecked, Source={x:Reference checkbox}}" />

测试代码中读取该属性并转换:

var element = Driver.FindElement(By.Id("checkbox"));
string isCheckedStr = element.GetAttribute("helpText");
bool.TryParse(isCheckedStr, out bool isChecked);

内容的提问来源于stack exchange,提问作者Alpay Çalışır

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:31:08