我开始为NetBeans 8
编写代码生成器,但我无法找出测试其invoke()
方法的最佳方法。
我想测试的代码生成器基本上是这样的:
(imports here)
public class MyCodeGenerator implements CodeGenerator {
private final JTextComponent textComponent;
private final CompilationController controller;
MyCodeGenerator(final Lookup context) {
textComponent = context.lookup(JTextComponent.class);
controller = context.lookup(CompilationController.class);
}
@Override
public String getDisplayName() {
return "Generate Some Code...";
}
/**
* This will be invoked when user chooses this Generator from Insert Code
* dialog
*/
@Override
public void invoke() {
if (textComponent != null && controller != null) {
controller.toPhase(Phase.RESOLVED);
//do more things with the source code;
}
}
}
我想使用一个模拟(Mockito)对象进行查找,以传递给MyCodeGenerator
的构造函数。模拟应该返回JTextComponent
和CompilationController
。
我知道我可以提供JTextComponent
测试代码,但是当我需要提供CompilationController
时,我就会碰壁。
我可以创建一个与JTextComponent
具有相同内容的临时java源文件,但我找不到从中创建CompilationController
(或WorkingCopy
)的方法。< / p>
这是我到目前为止所尝试的(我的测试方法):
@Test
public void testInvoke() throws ParseException, IOException {
System.out.println("invoke");
final ExtractControllerTask extractTask = new ExtractControllerTask(
Phase.RESOLVED);
final StringBuilder builder = new StringBuilder(100);
final JTextComponent textComponent;
final Document document;
final FileObject javaTestFile;
final OutputStream outputStream;
final JavaSource source;
builder.append("public class Clazz {");
builder.append("private int a = 2;");
builder.append("}");
textComponent = new JTextArea(builder.toString());
document = textComponent.getDocument();
document.putProperty(BaseDocument.MIME_TYPE_PROP, "text/x-java");
javaTestFile = FileUtil.createData(new File(
"/tmp/javaTestSourceFile.java"));
outputStream = javaTestFile.getOutputStream();
outputStream.write(builder.toString().getBytes());
outputStream.flush();
source = JavaSource.forFileObject(javaTestFile);
assertNotNull(source);
source.runUserActionTask(extractTask, true);
assertNotNull(extractTask.controller); //FAILS HERE
}
这是ExtractControllerTask的代码:
private static class ExtractControllerTask implements
Task<CompilationController> {
private final Phase targetPhase;
private CompilationController controller;
private ExtractControllerTask(final Phase phase) {
this.targetPhase = phase;
}
public void run(final CompilationController compControler) {
try {
compControler.toPhase(this.targetPhase);
this.controller = compControler;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}
让我感到惊讶的是run
中的ExtractControllerTask
方法永远不会被调用。
我真的需要测试我的代码,但我无法找到正确的方法。也许这种方法是完全错误的。
有人可以建议如何实现这个目标吗?