Skip to content Skip to sidebar Skip to footer

How To Unit Test Java Code That Dynamically Renders Html And Css?

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(...).a

Solution 1:

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.

Solution 2:

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.

Solution 3:

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})

Post a Comment for "How To Unit Test Java Code That Dynamically Renders Html And Css?"