使用 NUnit 的 WPF 切换按钮测试

WPF Toggle Button testing using NUnit

如何测试wpf切换按钮?我正在使用以下代码进行测试。

[Test]
    public void TestToggleButtonClick()
    {
        DataGrid_WpfToolkit dataGrid = window.Get<DataGrid_WpfToolkit>("Data");
        Assert.IsNotNull(dataGrid);
        ToggleButton toggle = dataGrid.Rows[0].Get<ToggleButton>("RowHeaderToggleButton");
        toggle.Toggle();
        Assert.AreEqual(false, dataGrid.Rows[0].IsSelected);

        toggle.Toggle();
        Assert.AreEqual(true, dataGrid.Rows[0].IsSelected);

        toggle.Toggle();
        Assert.AreEqual(false, dataGrid.Rows[0].IsSelected);
    }

以下代码是我的wpf应用程序中切换按钮点击事件的定义。

private void ToggleButton_Click(object sender, RoutedEventArgs e)
    {
            DependencyObject obj = (DependencyObject)e.OriginalSource;
            while (!(obj is DataGridRow) && (obj != null))
            {
                obj = VisualTreeHelper.GetParent(obj);
            }
            if (obj is DataGridRow)
            {
                if ((obj as DataGridRow).DetailsVisibility == Visibility.Visible)
                {
                    (obj as DataGridRow).IsSelected = false;
                    (obj as DataGridRow).DetailsVisibility = System.Windows.Visibility.Collapsed;

                    FrameworkElement tb2 = GetTemplateChildByName((obj as DataGridRow), "RowHeaderToggleButton");
                    (tb2 as ToggleButton).IsChecked = false;
                    flag = false;
                }
                else if ((obj as DataGridRow).DetailsVisibility == Visibility.Collapsed)
                {
                    for (int i = 0; i < Data.Items.Count; i++)
                    {
                        DataGridRow itm = GetDataGridRowitem(i);
                        itm.IsSelected = false;
                        itm.DetailsVisibility = System.Windows.Visibility.Collapsed;
                        FrameworkElement tb = GetTemplateChildByName(itm, "RowHeaderToggleButton");
                        (tb as ToggleButton).IsChecked = false;
                    }
                    DataTemplate dt = FindResource("tocchild") as DataTemplate;
                    Data.RowDetailsTemplate = dt;
                    (obj as DataGridRow).IsSelected = true;
                    (obj as DataGridRow).DetailsVisibility = Visibility.Visible;

                    FrameworkElement tb1 = GetTemplateChildByName((obj as DataGridRow), "RowHeaderToggleButton");
                    (tb1 as ToggleButton).IsChecked = true;
                    flag = true;
                }
            }}

但是toggle.Toggle()没有调用函数ToggleButton_Click()datagrid.Rows[0].IsSelected 总是 return 。在 ToggleButton_Click() 函数中,我将相应行的选择从 true 更改为 false 或将 false 更改为 true。但是控件没有进入函数ToggleButton_Click()。是否有任何其他方法可以从切换按钮调用 ToggleButton_Click() 函数?

方法有很多种:

  • 脏:使用反射或更改此方法的可访问性以从测试代码到达

  • 更改事件:使用Checked/Unchecked代替点击

  • 呼叫toggle.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

  • 使用UIAutomation (I prefer this way) (somekindofsample)