Correct way to modify the test task to depend on jar instead of classes directories

What is the correct way to modify the test task to depend on the jar created by the jar task instead of depending on the classes directories created by the classes task & its dependencies?

(I’m doing this from a plugin, not from a build script or buildSrc)

I’ve run into some issues when I tried to do this.

If someone already knows the correct methodology, there’s no need for me to bombard everyone with the problems I’ve encountered.

If no one know’s how to do this, then I can detail what I’ve tried so far, and what went wrong. Hopefully someone would then be able to help work around the issues I’ve encountered.

I think I’ve solved the issues I had, but, if someone knows the approved way to change the dependency, it would be useful to know it, in case I’ve missed something.

My current solution runs the following code in the apply(Project) method of my Plugin<Project>:

final Test test = (Test) project.getTasks().getByName(JavaPlugin.TEST_TASK_NAME);
final Jar  jar  = (Jar)  project.getTasks().getByName(JavaPlugin. JAR_TASK_NAME);


project.afterEvaluate(p -> {
    final SourceSetOutput jarSourceSetOutput = getSourceSet(jar).getOutput();