Android Gradle script in multi-module project
Let's see what we have here:

sourceSets.androidTest.allJava.each {
    ...
}



sourceSets leads to SourceSetContainer
.androidTest leads to a single SourceSet
.allJava leads to the allJava property on a SourceSet which leads to a SourceDirectorySet


Now, while there is not a .size() method or anything like it in SourceDirectorySet, or any of the super interfaces of that, there is some Groovy magic that provides a .size() method for all Iterables.

This means that you should be able to do the following:

def androidTestJavaSourceFileCount = sourceSets.androidTest.allJava.size()


Don't be fooled by this one-liner though, the source of the Iterable.size() method is:

public static int size(Iterable self) {
    return size(self.iterator());
}


which calls:

public static int size(Iterator self) {
    int count = 0;
    while (self.hasNext()) {
        self.next();
        count++;
    }
    return count;
}


So it will do the same thing as your previous code did, but it will clean up your part of the code.