Как протестировать ItemsControl с помощью TestStack.White.UIItems

Итак, я пытаюсь протестировать приложение UI WPF. Я использую фреймворк TestStack.White для тестирования. Пользовательский интерфейс имеет настраиваемый элемент управления DragDropItemsControl. Этот элемент управления наследуется от ItemsControl. Итак, как я могу проверить этот элемент управления.

<wpf:DragDropItemsControl x:Name="uiTabsMinimizedList"
                                      Margin="0 0 0 5"
                                      VerticalAlignment="Top"
                                      AllowDropOnItem="False"
                                      DragDropTemplate="{StaticResource TemplateForDrag}"
                                      ItemDropped="uiTabsMinimizedList_ItemDropped"
                                      ItemsSource="{Binding ElementName=uiMain,
                                                            Path=MinimizedTabs}"
                                      ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                                      ScrollViewer.VerticalScrollBarVisibility="Disabled"
                                      TextBlock.Foreground="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                                                                                                    AncestorType=UserControl},
                                                                     Path=Foreground}">
                <wpf:DragDropItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Border >
                            <TextBlock Cursor="Hand" Text="{Binding Panel.Label}" />
                        </Border>
                    </DataTemplate>
                </wpf:DragDropItemsControl.ItemTemplate>
            </wpf:DragDropItemsControl>

Можем ли мы протестировать?


person Qutfullo Ochilov    schedule 25.11.2016    source источник
comment
Вы спрашиваете, как вы можете дать каждому элементу в наборе индивидуальное имя/идентификатор автоматизации?   -  person LordWilmore    schedule 02.12.2016
comment
@LordWilmore Да. Я не нашел решения получить каждый элемент из ItemsControl.   -  person Qutfullo Ochilov    schedule 05.12.2016
comment
Таким образом, вам нужно установить для Automationproperties.automationid что-то уникальное. Поэтому выберите подходящую строку и добавьте префикс, который привязывается к чему-то уникальному внутри объекта, например. удостоверение личности.   -  person LordWilmore    schedule 06.12.2016


Ответы (1)


Вам нужно создать свой собственный AutomationPeer для вашего DragDropItemsControl и для вашего пользовательского элемента управления, после чего вы сможете определить AutomationId как идентификатор вашего объекта элемента.

public class DragDropItemsControl : ItemsControl
{
    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return new DragDropItemsAutomationPeer(this);
    }
}

Пользовательский класс AutomationPeer для вашего элемента управления.

public class DragDropItemsControlAutomationPeer : ItemsControlAutomationPeer
{
    public DragDropItemsControlAutomationPeer(DragDropItemsControl owner)
        : base(owner)
    {
    }

    protected override string GetClassNameCore()
    {
        return "DragDropItemsControl";
    }

    protected override ItemAutomationPeer CreateItemAutomationPeer(object item)
    {
        return new DragDropItemsControlItemAutomationPeer(item, this);
    }
}

Пользовательский класс AutomationPeer для ваших элементов управления. Важной частью здесь является реализация метода GetAutomationIdCore().

public class DragDropItemsControlItemAutomationPeer : ItemAutomationPeer
{
    public DragDropItemsControlItemAutomationPeer(object item, ItemsControlAutomationPeer itemsControlAutomationPeer)
        : base(item, itemsControlAutomationPeer)
    {
    }

    protected override string GetClassNameCore()
    {
        return "DragDropItemsControl_Item";
    }

    protected override string GetAutomationIdCore()
    {
        return (base.Item as MyTestItemObject)?.ItemId;
    }

    protected override AutomationControlType GetAutomationControlTypeCore()
    {
        return base.GetAutomationControlType();
    }
}

Для следующего кода xaml

<local:MyItemsControl x:Name="icTodoList" AutomationProperties.AutomationId="TestItemsControl">
    <local:MyItemsControl.ItemTemplate>
        <DataTemplate>
            <Border >
                <TextBlock Cursor="Hand" Text="{Binding Title}" />
            </Border>
        </DataTemplate>
    </local:MyItemsControl.ItemTemplate>
</local:MyItemsControl>

Инициализация в коде позади

public MyMainWindow()
{
    InitializeComponent();

    List<MyTestItemObject> items = new List<MyTestItemObject>();
    items.Add(new MyTestItemObject() { Title = "Learning TestStack.White", ItemId="007" });
    items.Add(new MyTestItemObject() { Title = "Improve my english", ItemId = "008" });
    items.Add(new MyTestItemObject() { Title = "Work it out", ItemId = "009" });

    icTodoList.ItemsSource = items;
}
public class MyTestItemObject
{
    public string Title { get; set; }
    public string ItemId { get; set; }
}   

Мы можем видеть в UIAVerify

UIAVerify screen

Пример кода для проверки значений

// retrieve the custom control
IUIItem theItemsControl = window.Get(SearchCriteria.ByAutomationId("008"));

if (theItemsControl is CustomUIItem)
{
    // retrieve the custom control container
    IUIItemContainer controlContainer = (theItemsControl as CustomUIItem).AsContainer();

    // get the child components
    WPFLabel theTextBlock = controlContainer.Get<WPFLabel>(SearchCriteria.Indexed(0));

    // get the text value
    string textValue = theTextBlock.Text;
}
person Maxwell77    schedule 02.02.2017