Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get annotated methods from gradle plugin

I'm developing a gradle plugin for android projects in kotlin and I need to scan the project source files in order to get all tests' names. I have implemented a directory scanner and I got an Arraylist<File> with all test classes.

I tried to apply reflection to this files but I got always a no class found exception. I suppose that the gradle plug in is trying to find the class inside the same gradle plugin the project instead of the Android project where the plugin is used.

Is there any way to scan each File object in my ArrayList and get all methods with the annotation @test?

like image 304
rdiaz82 Avatar asked May 27 '18 09:05

rdiaz82


1 Answers

Since what you have is a list of all the source files in your project, you'll need to iterate over them, opening each in turn and reading them (as text) to find any method name that follows an @Test annotation.

Depending on how strong your coding standards are, and how well they are followed, that might be almost trivial or quite hard. In our code base you could simply look for lines matching ^\s+@Test and then match the next line against ^\s+\w+\s+\w+\s+(\w+)\( to get the method name. (Or tokenize it, if you prefer.) That's pretty much your simplest possible case; if your code base uses @Ignore to disable tests, or someone wraps a test in a multi-line comment block (/* ... */), or if there can be strange formatting, missing access modifiers, etc. then your job will be harder.

Oh, and I wouldn't bother searching here for how to ignore comments in code - most of the first hits do it wrong. Errors include assuming that multi-line comments start at the beginning of a line (there is no leading content on a line that matches a multi-line comment start) and end at the end of a line; that if a line contains a multi-line comment start it does not also need to be checked for a single-line comment (which may comment out the multi-line comment start, depending on order), and other problems.

like image 73
DavidW Avatar answered Nov 12 '22 16:11

DavidW