Skip to content

ui::testing::TestContextMenuHost

Header: winui/testing/TestContextMenuHost.hpp.

Derives from ui::ContextMenuHost.

ContextMenuHost test double: records every menu a control asks to show and answers with a scripted choice instead of opening a popup.

Script the answer with pick() (by visible text) or pick_index() before the control's Element::handle_context_menu() runs; the script applies to the next show() only and then resets to a dismissal. Like the real menu, a separator or a disabled item can't be picked, so scripting one reads as a dismissal.

Example:

ui::testing::HeadlessTextMeasurer measurer;
ui::TextControl block{"orange text"};
block.set_selection_enabled(true);
(void)block.measure({400, 30}, measurer, ui::Theme::default_light());
block.arrange({0, 0, 400, 30});
block.select(0, 6);
ui::testing::set_focused(block, true);

ui::testing::TestClipboard       clipboard;
ui::testing::TestContextMenuHost menu;
ui::testing::set_clipboard(&clipboard);
menu.pick("Copy");
REQUIRE(block.handle_context_menu(ui::Point{5, 5}, menu));
REQUIRE(menu.show_count() == 1);
REQUIRE(clipboard.text() == "orange");

pick

void pick(std::string text)

Makes the next show() choose the first non-separator item whose text equals text. Overrides an earlier pick_index(); no match (or a disabled match) dismisses.

pick_index

void pick_index(std::size_t index)

Makes the next show() choose the item at index (separators count). Overrides an earlier pick(); an out-of-range, separator or disabled index dismisses.

show_count

int show_count() const

How many menus have been shown over this host's lifetime.

last_items

const std::vector<ContextMenuItem>& last_items() const

The items of the most recent show() (empty before the first one).

last_position

Point last_position() const

Where the most recent menu was anchored, in window DIPs (the caret for a keyboard-invoked menu).

last_texts

std::vector<std::string> last_texts() const

The last menu's item texts, separators as empty strings.

enabled

std::optional<bool> enabled(const std::string& text) const

The enabled state of the last menu's item with visible text text (nullopt: absent).

show

std::optional<std::size_t> show(Point position, const std::vector<ContextMenuItem>& items) override

Records position/items, bumps show_count(), and returns the scripted choice (then clears the script). Returns nullopt, a dismissal, when nothing pickable was scripted.