I have a a Java class that gets a form definition from database then renders html, javascript and css according to the form definition, its using a lot of “appendable.append(…).append(…)” to build the html snippets, which is error prone. Jsp and common templating framework(eg.FreeMarker) is not an option here as the javascript, css, html elements are all dynamic(depending on the form definition). and for some reasons, GWT is not an option either.
A straight forward way of unit testing this renderer is to hard code the expected html code then compare with the actual output, but then the test is very fragile.
What is the best way to unit test this kind of html renderer, please?
Thank you all in advance.
If you hard-code expected HTML values, your tests might be brittle, but they will probably catch most of your bugs. Another approach is to check for the presence of certain key or important tags in the HTML output. This approach is much more flexible, but might miss some bugs. To decide which you should use, consider how often you expect the HTML structure to change.
There’s a balance to be struck here. The more specific your test is, the most brittle it will be. But if you’re not specific enough, your test won’t catch any bugs. It takes practice to develop of feel for how specific to be.
However in general, brittle tests are very dangerous so they are probably the “greater evil”. If your tests flag a lot of false positives, you will start to ignore them and then they become useless. I’d suggest you go with verifying the presence of key tags.