Class MockVaadin
For internal use only. May be renamed or removed in a future release.
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidafterSessionClose(VaadinSession session, UIFactory uiFactory) Internal function, do not call directly.static voidClears the current UI from thread-locals without firing detach events.static voidClears thelastNavigationThreadLocal recorded bycloseCurrentUI(boolean).static voidSince Browserless Testing runs in the same JVM as the server and there is no browser, the boundaries between the client and the server become unclear.static voidcloseCurrentUI(boolean fireUIDetach) Clears the current UI.static SessionObjectscreateSessionObjects(VaadinServletService service) Creates a new session, request and response for the givenservice, but does NOT set any thread-locals or create a UI.static voidcreateUI(UIFactory uiFactory, VaadinSession session) Creates a UI with the given factory and attaches it to the given session, which must be the current one.static voidfireServiceDestroy(VaadinService service) Fires service destroy listeners on the given service.static voidfireServiceDestroyListeners(VaadinService service, ServiceDestroyEvent event) Fires the given service destroy event to the listeners registered on the given service, rethrowing any exception a listener throws.static voidfireSessionDestroyAndDrain(VaadinSession session) Fires session-destroy listeners onsessionand drains pendingVaadinSession.access(com.vaadin.flow.server.Command)tasks scheduled during destruction.static voidfireSessionInit(VaadinService service, VaadinSession session, VaadinRequest request) Fires session init listeners on the given service.static voidfireSessionInitListeners(VaadinService service, SessionInitEvent event) Fires the given session init event to the listeners registered on the given service, rethrowing any exception a listener throws.static Function<MockHttpSession, MockRequest> Returns the factory creating theMockRequestof each session.static StringReturns theUser-Agentevery mocked request reports.static booleanisRunningUIQueue(VaadinSession session) Internal function, do not call directly.static UIFollows the reload chain starting atuiand returns the UI that is live now: a reload detaches a UI and creates a fresh one for the same window, so a caller holding the detached UI must be redirected to its replacement.static voidrecordReloadReplacement(UI detached, UI created) Records thatdetachedwas replaced bycreatedduring a page reload, so thatliveUI(UI)can map the old UI to the new one.static voidstatic voidrunUIQueue(boolean propagateExceptionToHandler) static voidrunUIQueue(boolean propagateExceptionToHandler, VaadinSession session) Runs all tasks scheduled byUI.access(com.vaadin.flow.server.Command).static voidsetMockRequestFactory(Function<MockHttpSession, MockRequest> mockRequestFactory) Sets the factory creating theMockRequestof each session.static voidsetup()static voidstatic voidstatic voidstatic voidsetup(Routes routes, UIFactory uiFactory, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration) Mocks Vaadin for the current test method:static voidsetup(UIFactory uiFactory, VaadinServlet servlet) static voidsetup(UIFactory uiFactory, VaadinServlet servlet, Set<? extends Class<?>> lookupServices) static voidsetup(UIFactory uiFactory, VaadinServlet servlet, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration) Use this method when you need to provide a completely custom servlet (e.g.static voidsetup(VaadinServlet servlet) static VaadinServletServicesetupServlet(VaadinServlet servlet) static VaadinServletServicesetupServlet(VaadinServlet servlet, Set<? extends Class<?>> lookupServices) static VaadinServletServicesetupServlet(VaadinServlet servlet, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration) Initializes the givenservletand its service, but does NOT create a session, UI, or set any thread-locals.static voidsetUserAgent(String userAgent) Sets theUser-Agentevery mocked request reports.static voidtearDown()Cleans up and removes the Vaadin UI and Vaadin Session.static voidunlockRunningUIQueue(VaadinSession session) Internal function, do not call directly.
-
Method Details
-
setup
public static void setup(Routes routes, UIFactory uiFactory, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration) Mocks Vaadin for the current test method:MockVaadin.setup(new Routes().autoDiscoverViews("com.myapp"));The UI factory must provide a new, fresh instance of the UI, so that the tests start from a pre-known state. If you're using Spring and you're getting UI from the injector, you must reconfigure Spring to use prototype scope, otherwise an old UI from the UI scope or Session Scope will be provided.Sometimes you wish to provide a specific
VaadinServletService, e.g. to overrideVaadinService.loadInstantiators()and provide your own way of instantiating Views, e.g. via Spring or Guice. Please do that by extendingMockVaadinServletand overridingMockVaadinServlet.createServletService(DeploymentConfiguration). Please consultMockServiceon what methods you must override in your custom service. Alternatively, seeMockSpringServlet(in thebrowserless-test-springmodule) on how to extend your custom servlet and provide all necessary mocking code.- Parameters:
routes- all classes annotated withRoute; useRoutes.autoDiscoverViews()to auto-discover all such classes.uiFactory- producesUIinstances and sets them as current, by default simply instantiatesMockedUIclass.lookupServices- service classes to be provided to the lookup initializerconfiguration- custom Vaadin configuration, such as application properties, feature flags, lookup services and JavaScript handlers, to apply to the mocked environment.
-
setup
public static void setup(Routes routes, UIFactory uiFactory, Set<? extends Class<?>> lookupServices) - Parameters:
routes- the routes to registeruiFactory- creates the UI of each sessionlookupServices- service classes to be provided to the lookup initializer
-
setup
- Parameters:
routes- the routes to registeruiFactory- creates the UI of each session
-
setup
- Parameters:
routes- the routes to register
-
setup
public static void setup() -
setup
public static void setup(UIFactory uiFactory, VaadinServlet servlet, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration) Use this method when you need to provide a completely custom servlet (e.g.SpringServlet). Do not forget to create a specialized service which works in mocked environment. See below for details on how to do this.The UI factory must provide a new, fresh instance of the UI, so that the tests start from a pre-known state. If you're using Spring and you're getting UI from the injector, you must reconfigure Spring to use prototype scope, otherwise an old UI from the UI scope or Session Scope will be provided.
- Parameters:
uiFactory- producesUIinstances and sets them as current, by default simply instantiatesMockedUIclass.servlet- allows you to provide your own implementation ofVaadinServlet. You MUST overrideVaadinServlet.createServletServiceand construct a custom service which overrides important methods. Please consultcom.vaadin.browserless.mocks.MockServiceon what methods you must override in your custom service.lookupServices- service classes to be provided to the lookup initializerconfiguration- custom Vaadin configuration, such as application properties, feature flags, lookup services and JavaScript handlers, to apply to the mocked environment.
-
setup
public static void setup(UIFactory uiFactory, VaadinServlet servlet, Set<? extends Class<?>> lookupServices) - Parameters:
uiFactory- creates the UI of each sessionservlet- the servlet to initializelookupServices- service classes to be provided to the lookup initializer
-
setup
- Parameters:
uiFactory- creates the UI of each sessionservlet- the servlet to initialize
-
setup
- Parameters:
servlet- the servlet to initialize
-
setupServlet
public static VaadinServletService setupServlet(VaadinServlet servlet, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration) Initializes the givenservletand its service, but does NOT create a session, UI, or set any thread-locals. Call this when you need to share a single service across multiple independent sessions (multi-user testing).- Parameters:
servlet- the servlet to initializelookupServices- service classes to be provided to the lookup initializerconfiguration- custom Vaadin configuration, such as application properties, feature flags, lookup services and JavaScript handlers, to apply to the mocked environment. Lookup services defined by the configuration are used in addition to the ones given bylookupServices. JavaScript handlers are applied even to a servlet that is already initialized.- Returns:
- the initialized
VaadinServletService
-
setupServlet
public static VaadinServletService setupServlet(VaadinServlet servlet, Set<? extends Class<?>> lookupServices) - Parameters:
servlet- the servlet to initializelookupServices- service classes to be provided to the lookup initializer- Returns:
- the initialized
VaadinServletService
-
setupServlet
- Parameters:
servlet- the servlet to initialize- Returns:
- the initialized
VaadinServletService
-
recordReloadReplacement
Records thatdetachedwas replaced bycreatedduring a page reload, so thatliveUI(UI)can map the old UI to the new one.- Parameters:
detached- the UI the reload tore downcreated- the UI the reload created
-
liveUI
Follows the reload chain starting atuiand returns the UI that is live now: a reload detaches a UI and creates a fresh one for the same window, so a caller holding the detached UI must be redirected to its replacement. Returnsuiitself if it was never replaced.- Parameters:
ui- the UI to look up- Returns:
- the UI that currently shows the window of
ui
-
closeCurrentUI
public static void closeCurrentUI(boolean fireUIDetach) Clears the current UI. A UI that is closing, or any UI whenfireUIDetachis true, is closed and removed from its session the way Flow removes the UI of a closed or reloaded browser tab, which fires its detach listeners. Does nothing if there is no current UI.- Parameters:
fireUIDetach- whether to close and remove the UI even if it isn't closing.
-
tearDown
public static void tearDown()Cleans up and removes the Vaadin UI and Vaadin Session. You can call this function inafterEach{}block, to clean up after the test. This comes handy when you want to be extra-sure that the next test won't accidentally reuse old UI, should you forget to callsetup()properly.You don't have to call this function though;
setup()will overwrite any current UI/Session instances with a fresh ones. -
fireSessionDestroyAndDrain
Fires session-destroy listeners onsessionand drains pendingVaadinSession.access(com.vaadin.flow.server.Command)tasks scheduled during destruction. ThecurrentlyClosingSessionflag is set for the duration so theafterSessionCloserecreation hook (used by single-usersetup) is suppressed — multi-user callers manage their own session lifecycle.- Parameters:
session- the session
-
getUserAgent
Returns theUser-Agentevery mocked request reports. Defaults to Firefox 94 on Ubuntu Linux.- Returns:
- the user agent string
-
setUserAgent
Sets theUser-Agentevery mocked request reports. Call beforesetup(), since the value is read while the session is created.- Parameters:
userAgent- the user agent string
-
getMockRequestFactory
Returns the factory creating theMockRequestof each session.- Returns:
- the request factory
-
setMockRequestFactory
Sets the factory creating theMockRequestof each session. Override when a test needs a subclass ofMockRequest.- Parameters:
mockRequestFactory- the request factory
-
createSessionObjects
Creates a new session, request and response for the givenservice, but does NOT set any thread-locals or create a UI.Use this when you need to create multiple independent sessions for multi-user testing. The caller is responsible for setting thread-locals (via
VaadinSession.setCurrent(com.vaadin.flow.server.VaadinSession),CurrentInstance, etc.) and for creating the UI viacreateUI(com.vaadin.browserless.internal.UIFactory, com.vaadin.flow.server.VaadinSession).- Parameters:
service- the initialized Vaadin service (fromsetupServlet(com.vaadin.flow.server.VaadinServlet, java.util.Set<? extends java.lang.Class<?>>, com.vaadin.browserless.BrowserlessConfiguration))- Returns:
- the created session objects
-
createUI
Creates a UI with the given factory and attaches it to the given session, which must be the current one.- Parameters:
uiFactory- creates the UI of each sessionsession- the session
-
clientRoundtrip
public static void clientRoundtrip()Since Browserless Testing runs in the same JVM as the server and there is no browser, the boundaries between the client and the server become unclear. When looking into sources of any test method, it's really hard to tell where exactly the server request ends, and where another request starts.You can establish an explicit client boundary in your test, by explicitly calling this method. However, since that would be both laborous and error-prone, the default operation is that Browserless Testing pretends as if there was a client-server roundtrip before every component lookup via the
_get/_find/_expectNone/_expectOnecall. SeeTestingLifecycleHookfor more details.Calls the following:
runUIQueue()TestSignalEnvironment.runQueuedTasks(), which runs the queued Signals effects, for example of a signal changed on another threadJavaScriptDispatcher.dispatch(UI)which runs all blocks scheduled viaUI.beforeClientResponse(com.vaadin.flow.component.Component, com.vaadin.flow.function.SerializableConsumer<com.vaadin.flow.internal.ExecutionContext>)and sends the pending JavaScript to the simulated client, seeExecutedJavaScriptcleanupDialogs()
ErrorHandlerthen take a look atrunUIQueue()instead.- Throws:
IllegalStateException- if the environment is not mocked
-
isRunningUIQueue
Internal function, do not call directly.Returns whether
runUIQueue(boolean, com.vaadin.flow.server.VaadinSession)orunlockRunningUIQueue(VaadinSession)is running theUI.access(com.vaadin.flow.server.Command)commands ofsessionon the current thread, that is, whether the caller is such a command.- Parameters:
session- the session, not null.- Returns:
- true if the commands of the session are running on this thread.
-
unlockRunningUIQueue
Internal function, do not call directly.Releases one hold of the
sessionlock withVaadinSession.unlock(). When that is the last hold, Flow runs theUI.access(com.vaadin.flow.server.Command)commands queued for the session, andisRunningUIQueue(VaadinSession)reports them as running.- Parameters:
session- the session, not null.
-
runUIQueue
Runs all tasks scheduled byUI.access(com.vaadin.flow.server.Command).If
VaadinSession.getErrorHandler()is not set orpropagateExceptionToHandleris false, any exceptions thrown fromCommands scheduled via theUI.access(com.vaadin.flow.server.Command)will make this function fail. The exceptions will be wrapped inExecutionException. Generally it's best to keeppropagateExceptionToHandlerset to false to make any exceptions fail the test; however if you're testing how your own customVaadinSession.getErrorHandler()responds to exceptions then set this parameter to true.Called automatically by
clientRoundtrip()which is by default called automatically fromTestingLifecycleHook. You generally don't need to call this method unless you need to test yourErrorHandler.- Parameters:
propagateExceptionToHandler- defaults to false. If true andVaadinSession.getErrorHandler()is set, any exceptions thrown fromCommands scheduled via theUI.access(com.vaadin.flow.server.Command)will be redirected toVaadinSession.getErrorHandler()and will not be re-thrown from this method.session- the session to run the queue of, defaults toVaadinSession.getCurrent().- Throws:
IllegalStateException- if the environment is not mocked
-
runUIQueue
public static void runUIQueue(boolean propagateExceptionToHandler) - Parameters:
propagateExceptionToHandler- whether an exception thrown by a task is passed to the session's error handler instead of being rethrown
-
runUIQueue
public static void runUIQueue() -
afterSessionClose
Internal function, do not call directly.Only usable when you are providing your own implementation of
VaadinSession. SeeMockVaadinSessionon how to call this properly.- Parameters:
session- the sessionuiFactory- creates the UI of each session
-
fireSessionInit
public static void fireSessionInit(VaadinService service, VaadinSession session, VaadinRequest request) Fires session init listeners on the given service. Java-friendly static wrapper for the internal extension function.- Parameters:
service- the servicesession- the sessionrequest- the request the session was created for
-
fireServiceDestroy
Fires service destroy listeners on the given service. Java-friendly static wrapper for the internal extension function.- Parameters:
service- the service
-
clearCurrentUI
public static void clearCurrentUI()Clears the current UI from thread-locals without firing detach events. Useful for multi-user context where UIs are managed independently. -
fireSessionInitListeners
Fires the given session init event to the listeners registered on the given service, rethrowing any exception a listener throws.- Parameters:
service- the serviceevent- the event to fire
-
fireServiceDestroyListeners
Fires the given service destroy event to the listeners registered on the given service, rethrowing any exception a listener throws.- Parameters:
service- the serviceevent- the event to fire
-