如何对动态呈现 html 和 css 的 Java 代码进行单元测试? [英] How to unit test Java code that dynamically renders html and css?

查看:21
本文介绍了如何对动态呈现 html 和 css 的 Java 代码进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java 类,它从数据库中获取表单定义,然后根据表单定义呈现 html、javascript 和 css,它使用了很多appendable.append(...).append(...)"构建 html 片段,这很容易出错.Jsp 和通用模板框架(例如 FreeMarker)在这里不是一个选项,因为 javascript、css、html 元素都是动态的(取决于表单定义).出于某些原因,GWT 也不是一种选择.

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.

对该渲染器进行单元测试的一种直接方法是对预期的 html 代码进行硬编码,然后与实际输出进行比较,但该测试非常脆弱.

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.

请问对这种 html 渲染器进行单元测试的最佳方法是什么?

What is the best way to unit test this kind of html renderer, please?

先谢谢大家.

推荐答案

如果您对预期的 HTML 值进行硬编码,您的测试可能会很脆弱,但它们可能会捕获您的大部分错误.另一种方法是检查 HTML 输出中是否存在某些关键或重要标签.这种方法更加灵活,但可能会遗漏一些错误.要决定应该使用哪个,请考虑您希望 HTML 结构多久更改一次.

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.

这篇关于如何对动态呈现 html 和 css 的 Java 代码进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆