mhash17
mhash17

Reputation: 379

Import of test package not possible

I was trying to import the io.quarkus.test.* package into a class in the src/main dir of a project. But the IDE always complained about not finding this package even despite the fact it was there (Ctrl+click). Also maven told "cannot find symbol".

But when i moved this java file into the src/test dir, the IDE was able to find it and the import could be resolved.

How does this behavior come about? Can someone explain that to me?

Upvotes: 2

Views: 4508

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102795

To compile any given source file, javac first needs information about all the various types you reference inside it. even java.lang.String doesn't mean anything to a java compiler unless it can find the resource java/lang/String.class, or possibly if it has a java source file it can compile first, so that it then has a String.class file.

Fortunately, just about everywhere java has the 'boot classpath' (or in more modern versions, boot modules) which is where java.lang.String lives. Java knows where this boot location is and automatically includes the lot at all times.

But the rest, such as io.quarkus.test.stuff, that has to be either on the classpath, or on a source path, when the compiler runs.

The src/main source dir is compiled with various things on the classpath and sourcepath.

Your src/test dir, as well as all dependencies that are configured to be available solely in the test configuration, are not part of that path!

That's by design: You don't want to ship your unit tests, and therefore there is no need to ship e.g. junit.jar and all the other stuff you need solely to run tests, when shipping your app. If your src/main code accidentally refers to a file in src/test or any test-only dependency and your IDE just hooks it all up as normal, everything works fine on your machine, you ship it to the server (or turn into an installer and ship it to your customers), and then everything fails.

The conclusion is simple:

  • If you want access to tooling from the main source tree to stuff that is currently configured for 'test' deployment only, then that is no longer test deployment, and it needs to be moved. Note that the src/test dir usually gets access to all the stuff main needs, unless you went out of your way to configure your build in a very weird fashion. So this move will not cause issues in your test code.
  • If you have some code in src/main that you only really need for testing, it should be in src/test instead.

Upvotes: 2

Related Questions