Lets say i have a method in some class in my application's package:
import org.junit.jupiter.api.Test;
@Test
public void testFizBuzz() {
if (1 != 0)
throw new Exception("Test failed");
}
I want to:
- enumerate all classes/methods in the "current" package
- find methods tagged with a specified
@Annotation
- construct the class
- call the (parameterless) method
How can i do this in Java?
In .NET it's easy
Here's how you do it in .NET (in pseudo-Java):
//Find all methods in all classes tagged with @Test annotation,
//and add them to a list.
List<MethodInfo> testMethods = new ArrayList<>();
//Enumerate all assemblies in the current application domain
for (Assembly a : AppDomain.currentDomain.getAssemblies()) {
//Look at each type (i.e. class) in the assembly
for (Type t : a.getTypes()) {
//Look at all methods in the class.
for (MethodInfo m : t.getMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
//If the method has our @Test annotation defined: add it
if (m.IsDefined(typeof(org.junit.jupiter.api.Test), true))
testMethods.add(m);
}
}
}
And now that we have a List
of all methods with the @Test
annotation, it's just a matter of calling them:
//Call every test method found above
for (MethodInfo m : testMethods) {
Object o = Activator.CreateInstance(m.DeclaringType); //Construct the test object
m.Invoke(o, null); //call the parameterless @Test method
}
What is the JRE equivalent of the above?
Research Effort
- Get all methods with a particular annotation in a package (Question isn't about the current package. Accepted answer uses 3rd party library.)
- Java seek a method with specific annotation and its annotation element (Question is about a specific class, rather than finding the classes)
- How to find annotated methods in a given package?
- How to run all methods with a given annotation?
Aucun commentaire:
Enregistrer un commentaire