如何在SpringBoot应用程序中扩展SpannerRepository的@Repository接口上对默认方法进行单元测试?

问题描述 投票:0回答:1
import com.google.cloud.spanner.Key;
import com.google.common.flogger.FluentLogger;
import org.springframework.cache.annotation.Cacheable;
import com.google.cloud.spring.data.spanner.repository.SpannerRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface OrganisationRepository extends SpannerRepository<Organisation, Key> {

    @Cacheable("OrgCache")
    Organisation findByCode(String orgCode);

    default Organisation getByCode(String orgCode, Runnable loggedErrorMessage) {
        return Optional.ofNullable(this.findByCode(orgCode))
            .orElseThrow(() -> {
                loggedErrorMessage.run();
                return new ResourceNotFoundException(ErrorCode.ORG_NOT_FOUND.getErrorData(orgCode));
        });
    }
}

如何为 getByCode 编写单元测试? 我在 SpannerRepository 和 DataJpaTest 支持的限制之间陷入困境,无法找到解决办法......迄今为止最好的尝试:

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(SpringExtension.class)
@DataJpaTest
class OrganisationRepositoryTest {

    @Autowired
    OrganisationRepository organisationRepository;

    @Test
    void getByCode_LogsErrorMessageWhenNotFound() {
        StringBuilder sb = new StringBuilder();
        organisationRepository.getByCode("unknownOrgCode", ()-> sb.append("the error I want to log"));
        assertThat(sb.toString()).isEqualTo("the error I want to log");
    }
}

此测试失败并显示:

Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.core.ConnectionCallback

spring-boot google-cloud-spanner
1个回答
0
投票

此错误消息表明 Java 运行时环境无法找到类

org.springframework.jdbc.core.ConnectionCallback

以下是导致此错误的一些可能原因:

  1. 缺少依赖项:类

    org.springframework.jdbc.core.ConnectionCallback
    是 Spring JDBC 模块的一部分。确保您已在项目的构建配置中包含必要的 Spring JDBC 依赖项(例如 Maven 或 Gradle)。

  2. 不正确的类路径:检查类路径是否设置正确。类

    org.springframework.jdbc.core.ConnectionCallback
    应出现在类路径中包含的 JAR 文件之一中。验证包含此类的 JAR 文件是否存在且可访问。

  3. 版本不匹配:您可能使用的是不兼容版本的 Spring JDBC 库。确保您使用的 Spring JDBC 库的版本与项目依赖项中指定的版本匹配。

  4. 打包问题:如果您使用的是可执行的 JAR 或 WAR 文件,请确保打包文件中包含所需的 Spring JDBC 库。

仔细检查这些方面应该有助于解决

ClassNotFoundException
org.springframework.jdbc.core.ConnectionCallback

© www.soinside.com 2019 - 2024. All rights reserved.