Search code examples
javajunitthymeleaf

Thymeleaf-test test thtest files with objects in context created by java JUnit


I am generating a mail template as plain text/html and try to test it with thymeleaf-test.

I currently struggle with generating the context for the templates from the surrounding java JUnit code.

 @Test
 void testTheymeleaf() {
    TestExecutor executor = new TestExecutor();
    executor.execute("classpath:mail/testResults.thtest");
    Assertions.assertTrue(executor.isAllOK());
 }

How do I bring the context for processing the template to the executor?

I know I can do it from within the thtest-file but that is not a viable solution as the context contains multiple aggregated objects. (and additionally, the needed data in the context is already present from other tests and can be coppied).


Solution

  • I found a solution like so:

    public class WebProcessingContextBuilderWithJavaVariables extends WebProcessingContextBuilder {
    
        private final Map<String, Object> vars;
    
        public WebProcessingContextBuilderWithJavaVariables(Map<String, Object> variables) {
            vars = variables;
        }
    
        @Override
        protected void doAdditionalVariableProcessing(
                final ITest test,
                final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext,
                final Locale locale, final Map<String, Object> variables) {
    
            variables.putAll(vars);
        }
    }
    

    This class is used in the tests to set a custom executor which gets the variables for the context.

    @Test
    void someTest() {
        HashMap<String, Object> vars = new HashMap<>();
        vars.put("key", validations);
        executor.setProcessingContextBuilder(new WebProcessingContextBuilderWithJavaVariables(vars));
        executor.execute("classpath:template.thtest");
    
        Assertions.assertTrue(executor.isAllOK());
    }