Class BrowserlessUIContext
-
- All Implemented Interfaces:
-
com.vaadin.browserless.TesterWrappers,com.vaadin.browserless.locator.GeneratedLocators,com.vaadin.browserless.locator.Locators,java.lang.AutoCloseable
public class BrowserlessUIContext implements TesterWrappers, Locators, AutoCloseable
UI-level context for multi-user browserless testing.
Represents a single browser window (one UI instance). All DSL methods (navigate, find, findInView, test) automatically call activate before executing, which transparently switches the thread-local Vaadin state and security context to this window's user.
Instances of this class are thread-affine: they must be created, used, and closed on the same thread. The active context is held in a ThreadLocal and is not visible to other threads. This class is not safe for concurrent access from multiple threads.
This means you can freely interleave calls on different windows without explicit context switching:
window1.navigate(ViewA.class); window2.navigate(ViewB.class); // auto-switches to window2's user window1.find(Button.class).first(); // auto-switches back to window1's user- Since:
1.1
-
-
Field Summary
Fields Modifier and Type Field Description public final BrowserlessUserContextuserpublic UIui
-
Method Summary
Modifier and Type Method Description BrowserlessUserContextgetUser()Returns the user context that owns this window. UIgetUI()Returns the UI managed by this context. voidactivate()Activates this UI context on the current thread. <T extends Component> Tnavigate(Class<T> navigationTarget)Navigates this window to the given view class. <C, T extends Component, HasUrlParameter<C>> Tnavigate(Class<T> navigationTarget, C parameter)Navigates this window to the given view class with a URL parameter. <T extends Component> Tnavigate(Class<T> navigationTarget, Map<String, String> parameters)Navigates this window to the given view class with route parameters. <T extends Component> Tnavigate(String location, Class<T> expectedTarget)Navigates this window to the given location and validates the resulting view. static BrowserlessUIContextforComponent(Component component)Shorthand for ad-hoc component testing of a single component — no @Routeview required.static BrowserlessUIContextforComponent(BrowserlessConfiguration configuration, Component component)Shorthand for ad-hoc component testing of a single component, applying the given custom Vaadin configuration (application properties, feature flags, lookup services) to the mocked environment. static BrowserlessUIContextforComponent(Supplier<Component> componentFactory)Shorthand for ad-hoc component testing of a single component, taking a factory rather than a ready instance — no @Routeview required.static BrowserlessUIContextforComponent(BrowserlessConfiguration configuration, Supplier<Component> componentFactory)Shorthand for ad-hoc component testing of a single component built by a factory, applying the given custom Vaadin configuration (application properties, feature flags, lookup services) to the mocked environment. <T extends Component> ComponentQuery<T>find(Class<T> componentType)Gets a query object for finding components of the given type in this window's UI. <T extends Component> ComponentQuery<T>find(Class<T> componentType, Component fromThis)Gets a query object for finding components of the given type nested inside the specified component. <T extends Component> ComponentQuery<T>findInView(Class<T> componentType)Gets a query object for finding components of the given type inside the current view. <T extends ComponentTester<Y>, Y extends Component> Ttest(Y component)Wraps a component with the best matching ComponentTester. <T extends ComponentTester<Y>, Y extends Component> Ttest(Class<T> tester, Y component)Wraps a component in the given ComponentTester. HasElementgetCurrentView()Gets the current view displayed in this window. HasElementreload()Simulates the user reloading this window (pressing F5): the window's UI is detached and a fresh one is created in the same Vaadin session, then the current location is rendered again. <T extends Component> Treload(Class<T> expectedTarget)Simulates a page reload (see reload) and verifies the resulting view is of the expected type. voidroundTrip()Simulates a server round-trip, flushing pending component changes. voidfireShortcut(Key key, Array<KeyModifier> modifiers)Simulates a keyboard shortcut performed on the browser. booleanrunPendingSignalsTasks()Processes all pending Signals tasks with a default max wait time of 100 milliseconds. booleanrunPendingSignalsTasks(long maxWaitTime, TimeUnit unit)Processes all pending Signals tasks, waiting up to the specified timeout for the first task to arrive. StringgetExternalNavigationURL()Returns the URL from the last external navigation triggered by setLocation or open. StringgetExternalNavigationURL(String windowName)Returns the last URL opened with the given window name. Map<String, List<String>>getOpenedWindows()Returns a map of all windows opened via open or open, excluding navigations that target the current window ( _self,_parent,_top, empty, ornull).voidactivateLocatorContext()Hook for context-bound implementations to install Vaadin thread-locals before a locator is built. voidclose()Closes this UI context and detaches the UI. -
Methods inherited from class com.vaadin.browserless.TesterWrappers
popoverFor, popoverFor, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test, test -
Methods inherited from class com.vaadin.browserless.locator.Locators
find -
Methods inherited from class com.vaadin.browserless.locator.GeneratedLocators
activateLocatorContext, findAccordion, findAnchor, findAvatarGroup, findBigDecimalField, findBreadcrumbs, findButton, findCard, findCheckbox, findCheckboxGroup, findComboBox, findConfirmDialog, findContextMenu, findDatePicker, findDateTimePicker, findDecimalRangeSlider, findDecimalSlider, findDescriptionList, findDetails, findDialog, findDiv, findEmailField, findEmphasis, findGrid, findGridContextMenu, findH1, findH2, findH3, findH4, findH5, findH6, findHr, findImage, findInput, findIntegerField, findIntegerRangeSlider, findIntegerSlider, findListBox, findListItem, findLoginForm, findLoginOverlay, findMarkdown, findMasterDetailLayout, findMenuBar, findMessageInput, findMessageList, findMultiSelectComboBox, findMultiSelectListBox, findNativeButton, findNativeDetails, findNativeLabel, findNotification, findNumberField, findOrderedList, findParagraph, findPasswordField, findPopover, findPre, findRadioButton, findRadioButtonGroup, findRangeInput, findRouterLink, findSelect, findSideNav, findSpan, findSplitLayout, findSwitch, findTabSheet, findTabs, findText, findTextArea, findTextField, findTimePicker, findTreeGrid, findUnorderedList, findUpload, findUploadButton, findUploadDropZone, findUploadFileList, findVirtualList, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use, use -
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Method Detail
-
getUser
BrowserlessUserContext getUser()
Returns the user context that owns this window.
- Returns:
the parent user context
-
getUI
UI getUI()
Returns the UI managed by this context.
- Returns:
the UI instance
-
activate
void activate()
Activates this UI context on the current thread.
Sets all Vaadin thread-locals (VaadinService, VaadinSession, UI, VaadinRequest, VaadinResponse) to this window's values. If a SecurityContextHandler is configured and the previous active context belonged to a different user, the outgoing user's security context is automatically saved and this user's context is restored.
The security context is a per-user snapshot, not per-window: switching between windows of the same user does not save or restore security state, so mutations made by one window are observed by sibling windows.
This method is called automatically by all DSL methods. You only need to call it explicitly if you are accessing Vaadin APIs directly (e.g.
UI.getCurrent()).
-
navigate
<T extends Component> T navigate(Class<T> navigationTarget)
Navigates this window to the given view class.
- Parameters:
navigationTarget- the view class to navigate to- Returns:
the instantiated view
-
navigate
<C, T extends Component, HasUrlParameter<C>> T navigate(Class<T> navigationTarget, C parameter)
Navigates this window to the given view class with a URL parameter.
- Parameters:
navigationTarget- the view class to navigate toparameter- the URL parameter- Returns:
the instantiated view
-
navigate
<T extends Component> T navigate(Class<T> navigationTarget, Map<String, String> parameters)
Navigates this window to the given view class with route parameters.
These are the parameters of the route template, such as
orderIdof@Route("order/:orderId")— not query parameters. To navigate with a query string, write it into the location given to navigate.- Parameters:
navigationTarget- the view class to navigate toparameters- the route parameters of the target's route template, keyed by parameter name- Returns:
the instantiated view
-
navigate
<T extends Component> T navigate(String location, Class<T> expectedTarget)
Navigates this window to the given location and validates the resulting view.
The location is written the way it appears in the browser's address bar, so it may carry a query string and a fragment — for example
"order/ORD-1?tab=history", whose query parameters the view reads from the navigation event.- Parameters:
location- the navigation location string, optionally with a query string and a fragmentexpectedTarget- the expected view class- Returns:
the instantiated view
-
forComponent
static BrowserlessUIContext forComponent(Component component)
Shorthand for ad-hoc component testing of a single component — no
@Routeview required. Builds a self-contained, route-free application context via forComponent, opens one user and one window, and attaches the given component to that window's UI. The returned window owns its bundled BrowserlessApplicationContext, which is torn down when the window's UI detaches, so a single try-with-resources is enough:
This is a single-window shorthand: it captures the given instance, so opening further windows on the underlying context would re-parent the same component. It also constructs the component before any UI exists — if the component's constructor needstry (var window = BrowserlessUIContext.forComponent(new MyForm())) { window.findButton().withCaption("Save").click(); }UI.getCurrent()or the session, use forComponent instead. For multi-window, multi-user, or routed tests use forComponent with a fresh-instance factory, or the standardBrowserlessApplicationContext.create(...)+newUser().newWindow()chain.- Parameters:
component- the component to attach; must not benull- Returns:
a window with the component attached
-
forComponent
static BrowserlessUIContext forComponent(BrowserlessConfiguration configuration, Component component)
Shorthand for ad-hoc component testing of a single component, applying the given custom Vaadin configuration (application properties, feature flags, lookup services) to the mocked environment. Behaves like forComponent otherwise.
var configuration = BrowserlessConfiguration.builder() .withFeatureFlags("myExperimentalFeature").build(); try (var window = BrowserlessUIContext.forComponent(configuration, new MyForm())) { window.findButton().withCaption("Save").click(); }- Parameters:
configuration- the configuration to apply; must not benullcomponent- the component to attach; must not benull- Returns:
a window with the component attached
-
forComponent
static BrowserlessUIContext forComponent(Supplier<Component> componentFactory)
Shorthand for ad-hoc component testing of a single component, taking a factory rather than a ready instance — no
@Routeview required. Builds a self-contained, route-free application context via forComponent, opens one user and one window, and attaches the produced component to that window's UI:
The factory runs fromtry (var window = BrowserlessUIContext.forComponent(MyForm::new)) { window.findButton().withCaption("Save").click(); }UI.init(), after the Vaadin thread-locals (UI, session, security context) are installed, so a component whose constructor readsUI.getCurrent()observes the live environment — unlike forComponent, which receives an already-constructed instance. The returned window owns its bundled BrowserlessApplicationContext, which is torn down when the window's UI detaches.- Parameters:
componentFactory- supplies the component to attach; must not benull- Returns:
a window with the produced component attached
-
forComponent
static BrowserlessUIContext forComponent(BrowserlessConfiguration configuration, Supplier<Component> componentFactory)
Shorthand for ad-hoc component testing of a single component built by a factory, applying the given custom Vaadin configuration (application properties, feature flags, lookup services) to the mocked environment. Behaves like forComponent otherwise; the configuration is already in effect when the factory runs.
- Parameters:
configuration- the configuration to apply; must not benullcomponentFactory- supplies the component to attach; must not benull- Returns:
a window with the produced component attached
-
find
<T extends Component> ComponentQuery<T> find(Class<T> componentType)
Gets a query object for finding components of the given type in this window's UI.
The query walks the server-side component tree. A component that another component renders per item, such as the component a
ComponentRenderercolumn renders for a grid row, is rendered into the column and not into the tree, and the content of an overlay, such as a context menu, is attached only while the overlay is open. Neither is reachable this way, and the lookup returns an empty result rather than failing, so reach those components through the owning component tester instead:GridTester.getCellComponent(row, column)for grid cells,ContextMenuTester.open()and thenclickItem(...)for a context menu, andGridTester.contextMenu(row).open()for a grid context menu.- Parameters:
componentType- the type of component to search for- Returns:
a query object
-
find
<T extends Component> ComponentQuery<T> find(Class<T> componentType, Component fromThis)
Gets a query object for finding components of the given type nested inside the specified component.
Searches the same server-side component tree as find, see there for what that tree does not contain.
- Parameters:
componentType- the type of component to search forfromThis- the component to search within- Returns:
a query object
-
findInView
<T extends Component> ComponentQuery<T> findInView(Class<T> componentType)
Gets a query object for finding components of the given type inside the current view.
Searches the same server-side component tree as find, see there for what that tree does not contain.
- Parameters:
componentType- the type of component to search for- Returns:
a query object
-
test
<T extends ComponentTester<Y>, Y extends Component> T test(Y component)
Wraps a component with the best matching ComponentTester. This generic fallback is used for component types not covered by the specific TesterWrappers defaults.
- Parameters:
component- the component to wrap- Returns:
the component wrapped in a tester
-
test
<T extends ComponentTester<Y>, Y extends Component> T test(Class<T> tester, Y component)
Wraps a component in the given ComponentTester.
- Parameters:
tester- test wrapper to usecomponent- component to wrap- Returns:
the initialized tester for the component
-
getCurrentView
HasElement getCurrentView()
Gets the current view displayed in this window.
- Returns:
the current view
-
reload
HasElement reload()
Simulates the user reloading this window (pressing F5): the window's UI is detached and a fresh one is created in the same Vaadin session, then the current location is rendered again. Session-scoped state (session attributes, security context) survives, and sibling windows are unaffected. Views annotated with @PreserveOnRefresh keep their component instance and state; other views are recreated.
- Returns:
the view shown after the reload
- Since:
25.4
-
reload
<T extends Component> T reload(Class<T> expectedTarget)
Simulates a page reload (see reload) and verifies the resulting view is of the expected type.
- Parameters:
expectedTarget- the expected view class after reload- Returns:
the view shown after the reload
- Since:
25.4
-
roundTrip
void roundTrip()
Simulates a server round-trip, flushing pending component changes.
-
fireShortcut
void fireShortcut(Key key, Array<KeyModifier> modifiers)
Simulates a keyboard shortcut performed on the browser.
- Parameters:
key- primary key of the shortcut.modifiers- key modifiers.
-
runPendingSignalsTasks
boolean runPendingSignalsTasks()
Processes all pending Signals tasks with a default max wait time of 100 milliseconds. Convenience for tests that need to wait for asynchronous Signal effects triggered from background threads or non-UI contexts.
If this window's VaadinSession lock is held by the current thread, it is temporarily released during the wait to allow background threads to acquire the lock and enqueue tasks.
Confirmation of a write to a shared signal (for example
SharedValueSignalorSharedListSignal) is dispatched through the same queue. The new value is visible immediately throughpeek(), but theSignalOperationreturned by the write only completes once the queued confirmation task has been run by this method. Blocking onoperation.result().get()without draining the queue first never completes, because the confirmation task can only run on the thread that calls this method:var operation = tickets.insertLast("a ticket"); window.runPendingSignalsTasks(); assertTrue(operation.result().join().successful());- Returns:
trueif any pending Signals tasks were processed
-
runPendingSignalsTasks
boolean runPendingSignalsTasks(long maxWaitTime, TimeUnit unit)
Processes all pending Signals tasks, waiting up to the specified timeout for the first task to arrive. Once the first task is found, all remaining tasks in the queue are processed immediately without additional waiting.
- Parameters:
maxWaitTime- the maximum time to wait for the first task to arrive in the given time unit.unit- the time unit of the timeout value- Returns:
trueif any pending Signals tasks were processed
-
getExternalNavigationURL
String getExternalNavigationURL()
Returns the URL from the last external navigation triggered by setLocation or open.
This captures URLs where the window name is
_self,_parent,_top, empty, ornull(all of which navigate the current window). To query URLs opened in other windows, use getExternalNavigationURL or getOpenedWindows.- Returns:
the external navigation URL, or
nullif no external navigation has occurred
-
getExternalNavigationURL
String getExternalNavigationURL(String windowName)
Returns the last URL opened with the given window name.
For
_blank, returns the URL from the most recent call. For named windows, returns the last URL that targeted that name.- Parameters:
windowName- the window name to look up- Returns:
the last URL for the given window name, or
nullif none
-
getOpenedWindows
Map<String, List<String>> getOpenedWindows()
Returns a map of all windows opened via open or open, excluding navigations that target the current window (
_self,_parent,_top, empty, ornull).The map keys are window names, and values are lists of URLs opened under that name. For
_blank, the list contains all URLs (each call opens a new window). For named windows, the list typically contains a single entry (the last URL).- Returns:
an unmodifiable map of window names to URL lists
-
activateLocatorContext
void activateLocatorContext()
Hook for context-bound implementations to install Vaadin thread-locals before a locator is built. Default is a no-op.
-
close
void close()
Closes this UI context and detaches the UI.
-
-
-
-