【问题标题】:ClassNotFoundException on Spring JavaMailSenderImpl in JUnit test with Spring Boot使用 Spring Boot 进行 JUnit 测试中 Spring JavaMailSenderImpl 上的 ClassNotFoundException
【发布时间】:2017-04-22 11:54:12
【问题描述】:

我刚刚使用 Spring Boot 开始了一个新项目,我正在努力掌握它。我正在使用 Spring Tool Suite,它为我创建了一个 Spring Boot 项目并加载了一些我知道我需要进一步的依赖项(特别是 Spring Batch 和 Spring Data)

这是我的 pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-batch</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- JDBC driver -->
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>6.1.0.jre8</version>
    </dependency>
</dependencies>

我一直在阅读参考文档并且知道我会在某个时候需要邮件,所以我将它添加到我的 application.properties 文件中:

spring.mail.host=my.mail.host

然后我尝试使用mvn package 构建应用程序,但它在测试中引发了错误。测试包括以下内容:

package its.idcard.batch;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class IdCardBatchApplicationTests {

    @Test
    public void contextLoads() {
    }

}

所以它所做的只是尝试加载应用程序上下文,但它在 org.springframework.mail.javamail.JavaMailSenderImpl 上出现 ClassNotFoundException 失败。

我知道这纯粹是测试的问题,因为在添加了一些 Spring Data 内容并在 maven 中跳过测试后,我的存根应用程序按预期运行(查看生成的 jar,我可以看到 spring- context-support-4.3.4-RELEASE.jar 存在,包含有问题的类),所以它似乎是测试中的类路径问题,但我很难过。如果我注释掉属性文件中的spring.mail.host 行,测试运行没有问题。

任何想法都将不胜感激。

【问题讨论】:

  • 您需要添加 javax.mail 依赖项。尝试使用这个 javax.mailmail1.4.7
  • 这已经包含在spring-boot-starter-mail依赖中,所以不需要再次添加。

标签: maven junit spring-boot jakarta-mail


【解决方案1】:

我认为我刚刚遇到的问题似乎是我的 maven 存储库中损坏的 jar 文件。我决定在我的配置类中手动创建 MailSender bean 以查看是否有帮助,但 Eclipse 将该类标记为未找到,即使包含它的 jar 位于 maven 依赖项中。然后我从命令行尝试了mvn compile,这给了我一个更有用的错误,指示损坏的 jar,所以我从本地存储库中删除了有问题的 jar,并让 maven 重新下载它们,现在我不再收到错误在上面的配置中。

希望这对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 2018-05-25
    • 2021-12-17
    • 2021-01-24
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2019-08-23
    • 1970-01-01
    相关资源
    最近更新 更多