TL;DR: gradle testClasses compiles the test source code.
The tasks for compiling the test source code will not be needed when the test-task is excluded. Gradle sees that and won’t execute the unneeded tasks.
Here is the task dependency graph, when you exclude something all tasks that arent needed for other tasks will be dropped.

source Gradle User Guide
So looking at the task dependency graph testClasses is the task for compiling the test source code and processing the resources.
You could just add this task to your command,
gradle build testClasses -x test
Or even better use the assemble-task (build the jar) with the testClasses-task. With this, you do not have to exclude the tests.
gradle assemble testClasses