我正在将新需求开发成一段较旧的代码,并利用这个机会开始在一些单元测试中工作。遵循TDD和可能工作的最简单的事情。我遇到了一种情况,我无法决定什么是最佳实践。其中两个需求实际上非常相似,因此,随着代码的增长,有足够的机会进行重构。下面是具体的情况:
MethodOne()
{
int errorCode = sectionOfDiverseCode();
//SharedCode
string userMessage = localizeError(errorCode);
displayUserMessage(userMessage);
}
MethodTwo()
{
int errorCode = anotherSectionOfDiverseCode();
//SharedCode
string userMessage = localizeError(errorCode);
displayUserMessage(userMessage);
}
Currently I'm writing the same unit tests to fit the requirements that the string is localized correctly and also that it is displayed in the user interface. Would it better to isolate the localization and display methods and have one set of unit tests for them and then single test to confirm the two methods call these methods? Or is it better to write the localize and display tests for each method?发布于 2010-12-30 00:05:04
我建议为localizeError设置一组测试,并为displayUserMessage设置另一组测试。似乎没有任何理由将两者联系在一起;本地化的错误可能会记录到日志中,并且您可能希望显示非错误消息,对吧?
一般而言,请尽量保持单元测试的规模。他们的想法是测试一小部分代码,这样你就可以尽可能快地隔离和修复问题。
编辑:请记住,TDD不是灵丹妙药。在这种情况下,关键点是单元测试适用于localizeError和displayUserMessage,但您所描述的需求驱动测试可能不太适合methodOne和methodTwo。根据您的组织,也许更高级别的“检查是否正确显示”测试在UAT中更好。关于“不要重复自己”的一般指导原则和所有其他良好的软件开发规则也适用于编写测试。
https://stackoverflow.com/questions/4555634
复制相似问题