You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Maven依赖仅在src\test\java可用,如何让其同时支持src\main\java?

Fixing Maven Dependency Scope for Main and Test Directories

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:35:29