Maven依赖仅在src\test\java可用,如何让其同时支持src\main\java?
Hey there! I see the issue here—your JUnit and AssertJ dependencies are set with the test scope, which is why they're only available in src/test/java and not in src/main/java. Let's break this down and fix it.
Why this happens
The test scope in Maven tells the build system that the dependency should only be included in the test classpath. That means it's accessible to your test code, but not to your main application code.
How to make the dependencies work in both directories
To make these dependencies available in both src/main/java and src/test/java, you just need to remove the <scope>test</scope> line from each dependency. By default, Maven uses the compile scope, which includes the dependency in both the main and test classpaths.
Here's your updated pom.xml snippet:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <!-- Removed test scope; default compile scope applies --> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.9.0</version> <!-- Removed test scope; default compile scope applies --> </dependency>
A quick note of caution
While this change will solve your immediate problem, it's worth mentioning that frameworks like JUnit are designed specifically for testing. Using them in your main application code isn't a common practice and might indicate a design choice you should double-check. AssertJ, on the other hand, can be useful for runtime assertions in main code if that's what you need—so that part is totally fine.
内容的提问来源于stack exchange,提问作者J. Doem

