View Unit Testing

Last modified by Vincent Massol on 2026/11/14 16:05

Concept

This is about writing "unit" tests for code generated by the server-side for the "View" of the MVC model. Namely, it focuses on testing:

  • wiki pages (*.xml files)
  • velocity templates (*.vm files)

Strategy

Specifically the idea is to be able to write integration tests that use the real code except for all the environment parts (database queries, filesystem files, remote server calls, etc) which are mocked in the test. Whereas functional tests fully test everything in a running XWiki instance, View unit tests don't test the interactions with the environment, nor the execution in the browser (JS, CSS). On the other hand, View unit tests execute at a fraction of the cost of functional tests (3mn for a single functional test, < 1s for a View unit test, a few ms for a pure unit test in isolation).

The strategy is to write some functional tests since they are the only tests proving that a features works but to use View unit tests wherever possible to test the different paths of view resources (specifically the different paths taken by the scripts that execute inside of the view resources).

Page Unit Testing

The way those tests work is that the XML file representing the wiki pages are loaded from the filesystem into XWikiDocument instances and a stubbed environment is defined so that XWikiDocument can then be rendered in the desired syntax.


To write such a test starting with the followng steps (common to both Page Unit Testing and Template Unit Testing):

  • Make your POM depend on the org.xwiki.platform:xwiki-platform-test-page module:
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-test-page</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
  • Write a Java test class that extends PageTest
  • Possibly add some extra component registration that you need through existing annotations (*ComponentList annotations) or through the custom ComponentList annotation. Note that when extending PageTest this automatically brings some base components registration (the list defined in PageComponentList and ReferenceComponentList). Example of other existing annotations:
    • XWikiSyntax20ComponentList: XWiki Syntax 2.0-related components
    • XWikiSyntax21ComponentList: XWiki Syntax 2.1-related components
    • HTML50ComponentList: HTML 5.0-related components
    • XHTML10ComponentList: XHTML 1.0-related components

Then:

  • You then verify the rendering of a page by setting the output syntax you wish to have, the query parameters and then call renderPage(). For example:
    setOutputSyntax(Syntax.HTML_5_0);
    stubRequest.put("section", "Links");
    stubRequest.put("xpage", "print");
    ...
    String result = renderPage(new DocumentReference("xwiki", "XWiki", "XWikiSyntax"));
    assertTrue(result.contains("...content that we wish to verify..."), "...explanation if test fails");
  • If you need to have some other pages loaded from sources too (for example if the page you're rendering contains an include macro that loads another page), you'll use the

    loadPage() API as in:loadPage(new DocumentReference("xwiki", "XWiki", "XWikiSyntaxLinks"));

Here's a full example (imports omitted):

@XWikiSyntax20ComponentList
@HTML50ComponentList
class SettingsPageTest extends PageTest
{
    private static final DocumentReference SETTINGS =
        new DocumentReference("xwiki", "AnnotationCode", "Settings");

    private static final DocumentReference ANNOTATION_CONFIG =
        new DocumentReference("xwiki", "AnnotationCode", "AnnotationConfig");

    private static final DocumentReference COMMENTS_CLASS =
        new DocumentReference("xwiki", "XWiki", "XWikiComments");

    private static final DocumentReference TARGET = new DocumentReference("xwiki", "Space", "Target");

    private AnnotationScriptService annotationScriptService;

    @BeforeEach
    void setUp() throws Exception
    {
        // The annotation class referenced by the configuration. Only its "author" field is used, to render the label
        // of the filter criterion.
        XWikiDocument commentsClass = this.xwiki.getDocument(COMMENTS_CLASS, this.context);
        commentsClass.getXClass().addTextField("author", "Author", 30);
        this.xwiki.saveDocument(commentsClass, this.context);

        // The document holding the annotations.
        XWikiDocument target = this.xwiki.getDocument(TARGET, this.context);
        target.setSyntax(Syntax.XWIKI_2_1);
        this.xwiki.saveDocument(target, this.context);

        // The configuration provides the annotation class reference (XWiki.XWikiComments).
        loadPage(ANNOTATION_CONFIG);

        // The annotations displayed in the filters are provided by the annotation service.
        this.annotationScriptService = mock(AnnotationScriptService.class);
        this.componentManager.registerComponent(ScriptService.class, "annotations", this.annotationScriptService);

        this.stubRequest.put("target", "Space.Target");
    }

    @Test
    void authorIsEscapedInFilterCheckbox() throws Exception
    {
        String malformedAuthor = "\"><script>console.log(1)</script>";
        Annotation annotation = new Annotation("0");
        annotation.setAuthor(malformedAuthor);
        when(this.annotationScriptService.getAnnotations(any())).thenReturn(List.of(annotation));

        Document document = renderHTMLPage(SETTINGS);

        // The author is used as the value of the filtering checkbox. It must be escaped so that it stays inside the
        // attribute instead of breaking out of it.
        Element checkbox = document.selectFirst(".criterion-option-list input[type=checkbox]");
        assertNotNull(checkbox);
        assertEquals(malformedAuthor, checkbox.attr("value"));
        // The payload must not have been able to inject an executable script element.
        assertTrue(document.select("script").stream().noneMatch(script -> script.data().contains("console.log")),
            "The author payload was rendered as an executable script element");
    }
}

Template Unit Testing

To write such a test follow the common instruction.

Then:

  • Add the dependencies on the JAR modules containing the templates needed. For example if you need to load directly or indirectly some template located in the xwiki-platform-web-templates maven module (note that macros.vm is loaded automatically by VelocityManager), you'd write:
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-web-templates</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
  • You then use the TemplateManager to call the template to test. For example (JobStatusJSONPageTest, imports omitted):
    class JobStatusJSONPageTest extends PageTest
    {
        @Inject
        private TemplateManager templateManager;
    
        @MockComponent(classToMock = IconManagerScriptService.class)
        @Named("icon")
        private ScriptService iconManagerScriptService;
    
        @BeforeEach
        void setup()
        {
            when(((IconManagerScriptService)this.iconManagerScriptService).renderHTML(any(String.class)))
                .then(invocationOnMock -> invocationOnMock.getArgument(0) + "Icon");
        }
    
        @Test
        void nonExistingJob() throws Exception
        {
            this.stubRequest.put("jobId", "<test>");
            this.stubRequest.put("translationPrefix", "<test>");
    
            String output = this.templateManager.render("job_status_json.vm");
    
            assertThat(output.strip(), equalToCompressingWhiteSpace("""
                <div class="box errormessage ">
                <span class="icon-block">exclamationIcon</span>
                <span class="sr-only">error</span>
                <div>
                    &#60;test&#62;.notFound
                </div>
                </div>"""));
        }
    }

Loading a Wiki Macro

Loading a Java macro is straightforward and only requires to add the right components in the component list.
Loading a wiki macro requires a few more steps that are defined below.

  1. Add the following dependency to your module
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-rendering-wikimacro-store</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
      <type>test-jar</type>
    </dependency>
  2. Annotate your page test class with org.xwiki.rendering.wikimacro.internal.WikiMacroFactoryComponentClass
  3. Load the wiki macro page using org.xwiki.test.page.WikiMacroSetup#loadWikiMacro

Get Connected