Class MockVaadin

java.lang.Object
com.vaadin.browserless.internal.MockVaadin

public final class MockVaadin extends Object
Mocks the Vaadin environment: the servlet, the service, the session and the UI.

For internal use only. May be renamed or removed in a future release.

  • 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 override VaadinService.loadInstantiators() and provide your own way of instantiating Views, e.g. via Spring or Guice. Please do that by extending MockVaadinServlet and overriding MockVaadinServlet.createServletService(DeploymentConfiguration). Please consult MockService on what methods you must override in your custom service. Alternatively, see MockSpringServlet (in the browserless-test-spring module) on how to extend your custom servlet and provide all necessary mocking code.

      Parameters:
      routes - all classes annotated with Route; use Routes.autoDiscoverViews() to auto-discover all such classes.
      uiFactory - produces UI instances and sets them as current, by default simply instantiates MockedUI class.
      lookupServices - service classes to be provided to the lookup initializer
      configuration - 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 register
      uiFactory - creates the UI of each session
      lookupServices - service classes to be provided to the lookup initializer
    • setup

      public static void setup(Routes routes, UIFactory uiFactory)
      Parameters:
      routes - the routes to register
      uiFactory - creates the UI of each session
    • setup

      public static void setup(Routes routes)
      Parameters:
      routes - the routes to register
    • setup

      public static void setup()
    • setup

      public static void setup(UIFactory uiFactory, com.vaadin.flow.server.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 - produces UI instances and sets them as current, by default simply instantiates MockedUI class.
      servlet - allows you to provide your own implementation of VaadinServlet. You MUST override VaadinServlet.createServletService and construct a custom service which overrides important methods. Please consult com.vaadin.browserless.mocks.MockService on what methods you must override in your custom service.
      lookupServices - service classes to be provided to the lookup initializer
      configuration - 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, com.vaadin.flow.server.VaadinServlet servlet, Set<? extends Class<?>> lookupServices)
      Parameters:
      uiFactory - creates the UI of each session
      servlet - the servlet to initialize
      lookupServices - service classes to be provided to the lookup initializer
    • setup

      public static void setup(UIFactory uiFactory, com.vaadin.flow.server.VaadinServlet servlet)
      Parameters:
      uiFactory - creates the UI of each session
      servlet - the servlet to initialize
    • setup

      public static void setup(com.vaadin.flow.server.VaadinServlet servlet)
      Parameters:
      servlet - the servlet to initialize
    • setupServlet

      public static com.vaadin.flow.server.VaadinServletService setupServlet(com.vaadin.flow.server.VaadinServlet servlet, Set<? extends Class<?>> lookupServices, BrowserlessConfiguration configuration)
      Initializes the given servlet and 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 initialize
      lookupServices - service classes to be provided to the lookup initializer
      configuration - 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 by lookupServices. JavaScript handlers are applied even to a servlet that is already initialized.
      Returns:
      the initialized VaadinServletService
    • setupServlet

      public static com.vaadin.flow.server.VaadinServletService setupServlet(com.vaadin.flow.server.VaadinServlet servlet, Set<? extends Class<?>> lookupServices)
      Parameters:
      servlet - the servlet to initialize
      lookupServices - service classes to be provided to the lookup initializer
      Returns:
      the initialized VaadinServletService
    • setupServlet

      public static com.vaadin.flow.server.VaadinServletService setupServlet(com.vaadin.flow.server.VaadinServlet servlet)
      Parameters:
      servlet - the servlet to initialize
      Returns:
      the initialized VaadinServletService
    • recordReloadReplacement

      public static void recordReloadReplacement(com.vaadin.flow.component.UI detached, com.vaadin.flow.component.UI created)
      Records that detached was replaced by created during a page reload, so that liveUI(UI) can map the old UI to the new one.
      Parameters:
      detached - the UI the reload tore down
      created - the UI the reload created
    • liveUI

      public static com.vaadin.flow.component.UI liveUI(com.vaadin.flow.component.UI ui)
      Follows the reload chain starting at ui and 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. Returns ui itself 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 when fireUIDetach is 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 in afterEach{} 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 call setup() properly.

      You don't have to call this function though; setup() will overwrite any current UI/Session instances with a fresh ones.

    • fireSessionDestroyAndDrain

      public static void fireSessionDestroyAndDrain(com.vaadin.flow.server.VaadinSession session)
      Fires session-destroy listeners on session and drains pending VaadinSession.access(com.vaadin.flow.server.Command) tasks scheduled during destruction. The currentlyClosingSession flag is set for the duration so the afterSessionClose recreation hook (used by single-user setup) is suppressed — multi-user callers manage their own session lifecycle.
      Parameters:
      session - the session
    • getUserAgent

      public static String getUserAgent()
      Returns the User-Agent every mocked request reports. Defaults to Firefox 94 on Ubuntu Linux.
      Returns:
      the user agent string
    • setUserAgent

      public static void setUserAgent(String userAgent)
      Sets the User-Agent every mocked request reports. Call before setup(), since the value is read while the session is created.
      Parameters:
      userAgent - the user agent string
    • getMockRequestFactory

      public static Function<MockHttpSession,MockRequest> getMockRequestFactory()
      Returns the factory creating the MockRequest of each session.
      Returns:
      the request factory
    • setMockRequestFactory

      public static void setMockRequestFactory(Function<MockHttpSession,MockRequest> mockRequestFactory)
      Sets the factory creating the MockRequest of each session. Override when a test needs a subclass of MockRequest.
      Parameters:
      mockRequestFactory - the request factory
    • createSessionObjects

      public static SessionObjects createSessionObjects(com.vaadin.flow.server.VaadinServletService service)
      Creates a new session, request and response for the given service, 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 via createUI(com.vaadin.browserless.internal.UIFactory, com.vaadin.flow.server.VaadinSession).

      Parameters:
      service - the initialized Vaadin service (from setupServlet(com.vaadin.flow.server.VaadinServlet, java.util.Set<? extends java.lang.Class<?>>, com.vaadin.browserless.BrowserlessConfiguration))
      Returns:
      the created session objects
    • createUI

      public static void createUI(UIFactory uiFactory, com.vaadin.flow.server.VaadinSession session)
      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 session
      session - 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/_expectOne call. See TestingLifecycleHook for more details.

      Calls the following:

      If you'd like to test your ErrorHandler then take a look at runUIQueue() instead.
      Throws:
      IllegalStateException - if the environment is not mocked
    • isRunningUIQueue

      public static boolean isRunningUIQueue(com.vaadin.flow.server.VaadinSession session)
      Internal function, do not call directly.

      Returns whether runUIQueue(boolean, com.vaadin.flow.server.VaadinSession) or unlockRunningUIQueue(VaadinSession) is running the UI.access(com.vaadin.flow.server.Command) commands of session on 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

      public static void unlockRunningUIQueue(com.vaadin.flow.server.VaadinSession session)
      Internal function, do not call directly.

      Releases one hold of the session lock with VaadinSession.unlock(). When that is the last hold, Flow runs the UI.access(com.vaadin.flow.server.Command) commands queued for the session, and isRunningUIQueue(VaadinSession) reports them as running.

      Parameters:
      session - the session, not null.
    • runUIQueue

      public static void runUIQueue(boolean propagateExceptionToHandler, com.vaadin.flow.server.VaadinSession session)
      Runs all tasks scheduled by UI.access(com.vaadin.flow.server.Command).

      If VaadinSession.getErrorHandler() is not set or propagateExceptionToHandler is false, any exceptions thrown from Commands scheduled via the UI.access(com.vaadin.flow.server.Command) will make this function fail. The exceptions will be wrapped in ExecutionException. Generally it's best to keep propagateExceptionToHandler set to false to make any exceptions fail the test; however if you're testing how your own custom VaadinSession.getErrorHandler() responds to exceptions then set this parameter to true.

      Called automatically by clientRoundtrip() which is by default called automatically from TestingLifecycleHook. You generally don't need to call this method unless you need to test your ErrorHandler.

      Parameters:
      propagateExceptionToHandler - defaults to false. If true and VaadinSession.getErrorHandler() is set, any exceptions thrown from Commands scheduled via the UI.access(com.vaadin.flow.server.Command) will be redirected to VaadinSession.getErrorHandler() and will not be re-thrown from this method.
      session - the session to run the queue of, defaults to VaadinSession.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

      public static void afterSessionClose(com.vaadin.flow.server.VaadinSession session, UIFactory uiFactory)
      Internal function, do not call directly.

      Only usable when you are providing your own implementation of VaadinSession. See MockVaadinSession on how to call this properly.

      Parameters:
      session - the session
      uiFactory - creates the UI of each session
    • fireSessionInit

      public static void fireSessionInit(com.vaadin.flow.server.VaadinService service, com.vaadin.flow.server.VaadinSession session, com.vaadin.flow.server.VaadinRequest request)
      Fires session init listeners on the given service. Java-friendly static wrapper for the internal extension function.
      Parameters:
      service - the service
      session - the session
      request - the request the session was created for
    • fireServiceDestroy

      public static void fireServiceDestroy(com.vaadin.flow.server.VaadinService service)
      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.
    • clearLastNavigation

      public static void clearLastNavigation()
      Clears the lastNavigation ThreadLocal recorded by closeCurrentUI(boolean).

      closeCurrentUI(boolean) records the closing UI's active view location into lastNavigation so that the immediately following createUI(com.vaadin.browserless.internal.UIFactory, com.vaadin.flow.server.VaadinSession) call (in the single-user reload / session-recreation flow) can restore that location on the new UI. Multi-user lifecycle close paths (BrowserlessUIContext.close) call closeCurrentUI(boolean) without a matching createUI(com.vaadin.browserless.internal.UIFactory, com.vaadin.flow.server.VaadinSession), so this method must be invoked afterwards to prevent the recorded location from leaking into the next unrelated createUI(com.vaadin.browserless.internal.UIFactory, com.vaadin.flow.server.VaadinSession) on the same thread (e.g. user.newWindow()). Also clears the recorded window name for the same reason: a fresh window must get a new unique name, not inherit the closed window's name.

    • fireSessionInitListeners

      public static void fireSessionInitListeners(com.vaadin.flow.server.VaadinService service, com.vaadin.flow.server.SessionInitEvent event)
      Fires the given session init event to the listeners registered on the given service, rethrowing any exception a listener throws.
      Parameters:
      service - the service
      event - the event to fire
    • fireServiceDestroyListeners

      public static void fireServiceDestroyListeners(com.vaadin.flow.server.VaadinService service, com.vaadin.flow.server.ServiceDestroyEvent event)
      Fires the given service destroy event to the listeners registered on the given service, rethrowing any exception a listener throws.
      Parameters:
      service - the service
      event - the event to fire