gpt4 book ai didi

java - 重构测试

转载 作者:行者123 更新时间:2023-11-29 03:58:20 24 4
gpt4 key购买 nike

我有一段代码大致等同于以下内容。


public class ConcreteThread extends OtherThread {
private DAOfirst firstDAO;
private DAOsecond secondDAO;
private TransformService transformService;
private NetworkService networkService;

public ConcreteThread(DAOfirst first, DAOsecond second, TransformService service1,
NetworkService service2) {
firstDAO = first;
secondDAO = second;
transformService = service1;
networkService = service2;
}

public Future go() {
Results r1 = firstDAO.getResults();
MyCallable c1 = new MyCallable(r1);
return super.getThreadPool().submit(c1);
}

private class MyCallable implements Callable {
private Results result;
private Long count;
private MyCallable(Results r) {
this.result = r;
this.count = new Long(0);
}

public Long call() {
Singleton transactions = Singleton.getInstance();
try {
transactions.begin();
while(result != null) {
Transformed t = transformService.transform(r1);
networkService.sendSomewhere(t);
count = count += result.size();
secondDao.persist(result);
result = firstDao.getNext(result);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
transactions.end();
}
}
}

这些类(内部类或外部类)都没有单元测试,事实证明内部类 MyCallable 中存在错误。在我上面提供的代码的简化版本中,错误不存在。

因此,假设您决定修复错误,并为 MyCallable 实现一些单元测试。我的问题是这样的;您将如何为 MyCallable 内部类编写单元测试?

我自己的解决方案是先重构MyCallableConcreteThreadMyCallable 在其自己的文件中成为一个公共(public)类,ConcreteThread 现在将 DAO、服务和 Singleton 作为构造函数参数传递给 MyCallable,而不是而不是依赖内部类访问它的私有(private)变量。

然后我在单元测试中大量使用 EasyMock 来模拟这些依赖项并验证它们是否以我预期的方式被调用。

所有这一切的结果是 MyCallable 的代码比原来大了一些。由于它不再能够访问 ConcreteThread 中的私有(private)变量,ConcreteThread 必须将它们作为参数传入构造函数,而 MyCallable 将它们设置为私有(private)变量。

您认为这是错误的做法吗?也许通过执行这种重构我已经破坏了封装并向代码库添加了不必要的样板文件?您会在测试中使用反射吗?

最佳答案

A consequence of all this is that the code for MyCallable is somewhat larger than it was. As it no longer has access to the private variables in ConcreteThread, ConcreteThread must pass them in as arguments in the constructor, and MyCallable sets them as private variables.

这是一个很好的结果,MyCallable 不再依赖于 ConcreteThread 的变化。

我认为问题和答案都非常主观,但我认为您遵循了 SOLID重构原则(这是一件好事)。

如果可以的话,让 MyCallable 包 protected ,而不是公开:)

关于java - 重构测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5040588/

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