Reputation: 119
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.
Upvotes: 3
Views: 2843
Reputation: 2351
The approach you mentioned of comparing is a good approach, it is called the "golden master" approach to testing.
there is a verification library that works with junit to do this, that greatly simplifies the process called Approval Tests http://www.approvaltests.com
This also help protect against the brittleness by using reporters that will open your results and/or your golden master in either a diff reporter or a web browser.
The call you are looking for is:
Approvals.VerifyHtml(yourHtml)
and you will want to decorate your test with one of either
@UseReporter(DiffReporter.class)
@UseReporter(FileLauncherReporter.class)
@UseReporter({DiffReporter.class, FileLauncherReporter.class})
Upvotes: 1
Reputation: 13097
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.
Upvotes: 4
Reputation: 10250
I would take a two-pronged approach. First, you want to verify the individual snippets that you're generating. Your tests should validate that those components work as expected. Second, you should verify that each document produced as a whole is valid and consistent for its type. There are third-party tools that perform this validation for you. See http://www.w3.org/QA/Tools/ for some examples.
Upvotes: 2