gpt4 book ai didi

java - 将测试驱动开发引入遗留代码

转载 作者:搜寻专家 更新时间:2023-11-01 03:39:11 25 4
gpt4 key购买 nike

给定:一个 LegacyControllerClass 扩展了一个 MonsterFrameworkClass(人们多年来一直使用的非常令人讨厌的框架的一部分)。框架类做了很多神奇的事情,从默认构造函数中的大量逻辑到反射加载类的静态 block 。

LegacyControllerClass 中有很多生命周期方法,它们会改变全局状态。 execute() 方法是一个千行,具有您能想到的所有弊端。

public class LegacyControllerClass extends MonsterFrameworkClass {

//Life-cycle method
public void validate(){...}

//Life-cycle method
public void preExecute() {...}

//Life-cycle method
public void execute() {
//oodles of legacy code here:
// examples: call static methods of 'Util' classes
// lots of new X().y(..)
// call databases, services
// Even call super.execute()!!
// More rubbish
// More rubbish
}
}

好了,现在 Action 的场景就是execute()方法了。我正在向这些穷人介绍测试驱动开发,通过测试他们称之为“故事”的项目。 “故事”涉及向 responseProperties 添加错误消息,以便 View (jsp) 可以读取并显示它。伪代码是这样的:

if (error) {
Build the error message
Add the error message into the responseProperties
}

不幸的是,这段代码必须在 execute() 方法中的垃圾之间进行沙巫处理。

我的问题是:我能做的最好的事情是什么?我能想到的解决方案是:

  1. 提取两个方法 rubbish1()rubbish2()
  2. 以任何期望在我的测试代码中将它们 stub (例如;- 设置错误标志)
  3. 将我的代码放在 rubbish1()rubbish2() 之间

我开始以这种方式实现它,但 MonsterFrameworkClass 确实妨碍了我:像静态加载、加载随机属性文件的 ResourceBundle 的构造函数魔法,等等

是否有其他处理方法?

极小的免责声明:我肯定会购买 Michael Feather 的“使用遗留代码”并吞下它,但 SO 似乎是一个唾手可得的果实。

最佳答案

垃圾重构为方法很好。现在您可以下载 Powermock 来模拟代码中的所有可怕的垃圾。完成模拟后,您可以测试代码。

如果您不向这个怪物添加任何东西,那就更好了。您可以通过为新内容编写您自己的类,将您的功能组合到 MonstrosityRubbish(或其他)中。

最主要的是尽可能不要触及任何遗留代码,您可以将代码组合到其中。

所以在代码中:

private MyShinyClass yourShinyObject; // init

public void execute(Param param0) {
rubbish1();
yourShinyObject.handleError(param0);
rubbish2();
}

public class MyShinyClass {

public void handleError(Param param0) {
// your code here
}
}

如果你能设法像这样编写你的新东西,你将只依赖于可以被模拟/ stub 的 Param 并且你的代码可以被测试而不会让你的头发着火。

如果您能以函数式方式编写它就更好了,这样您就不必在分离的代码中操作 responseProperties:

public void execute(Param param0) {
rubbish1();
responseProperties.add(yourShinyObject.fetchErrors(param0));
rubbish2();
}

public class MyShinyClass {

public List<HopelessError> fetchErrors(Param param0) {
// your code here
}
}

当然 execute() 不需要参数,您可以将任何您想要的变量/字段传递给 handleErrors()

关于java - 将测试驱动开发引入遗留代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com