你好我的Java有点生疏,所以请耐心等待。我的任务是减少研究项目中重复代码的数量,因此我认为我无法在此处发布任何代码。但基本上,我有大约20个不同类别的大致相同的方法(测试方法),我一直在尝试两种不同的方法来解决这个问题,但我遇到了每个问题。将变量传递到使用其他方法或继承的方法
我发现,以减少重复第一种方式是,以除去包含在所有的试验方法初始变量并将其放置在一个单独的方法(制备方法)类的超类的内部和具有它称为测试方法。这个解决方案的问题不是在准备方法中声明的所有变量将保持本地状态,并且一旦在另一个方法中调用该方法时就会被擦除?
我的第二个想法是让超类的所有变量字段,并让它们被子类继承。这个解决方案几乎可以工作,除了其中一个变量IFile importedFile = importFile(file);
是创建这些变量所必需的变量之一,它必须包含抛出异常所包含的任何内容,我不相信你可以用类来完成。
我一直希望有人能够用这些解决方案之一指出我正确的方向,或者可能会提出另一个我一直无法找到的解决方案。
我忘了提及的一点是,除了初始变量之外,每种测试方法在写入测试方法时略有不同。 编辑:如果不是这样的话,我会把这个方法拉进超类,并且完成它。
编辑:下面是测试方法,我使用了超类的部分,
// method inside of the subclass
public void test() throws Exception {
// variables removed and placed in AbstractTest
for (int i = 0; i < expectedExitNodeCount; i++) {
if (markerFields.peekFirst().equalsIgnoreCase("EXPOSED_EXIT")) {
expectedExitNodes.add(new CTrueExitNode());
} else {
fromLine = Integer.parseInt(markerFields.removeFirst().trim());
fromCol = Integer.parseInt(markerFields.removeFirst().trim());
toLine = Integer.parseInt(markerFields.removeFirst().trim());
toCol = Integer.parseInt(markerFields.removeFirst().trim());
length = length(ast, fromLine, fromCol, toLine, toCol);
assertTrue(length > 0);
ICFlowNode expectedExit = findNode(ast, ICFlowNode.class, fromLine, fromCol, length);
assertNotNull(expectedExit);
expectedExitNodes.add(expectedExit);
}
}
// additional code omitted from method
}
// Superclass the variables have been placed in.
public abstract class AbstractTestCase extends WorkTest {
protected File file;
protected String markerText;
public AbstractTestCase(String name, VPG< ? , ? , ? > vpg) {
super(name, vpg);
}
protected void prepare() throws Exception {
// Variables used in the test method
IFile importedFile = importFile(file);
project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
CVPG.getInstance().ensureVPGIsUpToDate();
CTranslationUnit ast = CVPG.getInstance().acquireTransientAST(
ResourceUtil.getFilenameForIFile(importedFile));
LinkedList<String> markerFields = MarkerUtil.parseMarker(markerText);
int fromLine = Integer.parseInt(markerFields.removeFirst().trim());
int fromCol = Integer.parseInt(markerFields.removeFirst().trim());
int toLine = Integer.parseInt(markerFields.removeFirst().trim());
int toCol = Integer.parseInt(markerFields.removeFirst().trim());
int length = length(ast, fromLine, fromCol, toLine, toCol);
assertTrue(length > 0);
IASTNode node = findNode(ast, IASTNode.class, fromLine, fromCol, length);
assertNotNull(node);
Integer expectedExitNodeCount = Integer.parseInt(markerFields.removeFirst().trim());
Set<ICFlowNode> expectedExitNodes = new HashSet<ICFlowNode>();
}
protected void test() throws Exception {
//Considered making test a inherited method
}
}
你面临的例外是什么? –
这将很难帮助删除无代码的轻微差异的重复。请求权限发布它或提出一个遵循相同模式的假示例。 –
“每种测试方法略有不同”...有时[Template method pattern](http://en.wikipedia.org/wiki/Template_method)可以处理这种性质的重复。 – ajb