2016-11-25 2 views
2

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

<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> 

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

+0

Вы спрашиваете, как вы можете дать каждому элементу в наборе индивидуальное имя/AutomationId? – LordWilmore

+0

@LordWilmore Да. Я не нашел никакого решения получить каждый элемент из ItemsControl –

+0

Так что вам нужно настроить automationproperties.automationid на что-то уникальное. Поэтому выберите подходящую строку и добавьте префикс, который связывается с чем-то в уникальном объекте, например. идентификатор. – LordWilmore

ответ

0

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

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> 

Init в коде позади

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

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

// 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; 
} 
Смежные вопросы