问题
I'm trying the following, suggested by Cedric Beust in some other thread.
You could do this yourself as a pre-test task: implement a code generator that takes the information in XML form, grab the corresponding Java source file and generate a TestNG source file with all the annotations placed in the right locations. And then you run TestNG on that file.
I have no clue with code generation. Can someone guide me in the right direction? Some simple examples would be great.
Update: This is the template of what I would like to generate.
public class <tobeReadFromConfigFile>
{
@Test(groups="to be read from config file")
public void <tobereadfromconfigfile>{
//to be read from config file(Name of function to call)
//to be read from config file(Name of function to call)
//to be read from config file(Name of function to call)
}
.
.
.
}
The code inside function will be just function calls, which has to be read and copied exactly from config file.
回答1:
A FreeMarker template would look something like this:
public class ${className} {
@Test(groups="${testGroups}")
public void ${testMethodName}() {
<#list methods as m>
${m}
</#list>
}
}
It would be filled from a context, essentially a hashmap with className
, testGroups
, etc. entries, that would be read from your XML file. methods
would be a Collection
(like a list), also read from the XML file.
There are many other templating libraries, of course; this is just an example.
FreeMarker
回答2:
I have written an eclipse plugin that uses freemarker templates and provides the context of named java classes as ICompilationUnit from org.eclipse.jdt.core. You can check it out at https://github.com/karajdaar/templator
来源:https://stackoverflow.com/questions/11040968/generating-java-files-and-using-them-at-runtime