无法使用带注释的测试类测试 Redis 存储库@DataRedisTest

Unable to test Redis repository with @DataRedisTest annotated test class

提问人:efk 提问时间:11/4/2023 最后编辑:efk 更新时间:11/5/2023 访问量:29

问:

我正在尝试为我的Spring Boot应用程序的Redis存储库编写单元测试。但是,当我运行测试用例时,自动连接的存储库对象会导致以下异常:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.mycomp.myapi.repository.UserRepositoryTest': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycomp.myapi.repository.UserRepositoryTest' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at 

@DataRedisTest注解应该自动连接存储库对象,但事实并非如此。哪里出了问题或遗漏了什么?任何帮助将不胜感激。

Spring Boot版本:2.6.6

我使用嵌入式 Redis 进行测试。我的 maven 依赖项是:

<dependency>
            <groupId>it.ozimov</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.7.2</version>
            <scope>test</scope>
</dependency>

我的嵌入式 Redis 配置类是:

@TestConfiguration
public class TestRedisConfiguration {

    private RedisServer redisServer;

    public TestRedisConfiguration() {
        this.redisServer = new RedisServer(6370);
    }

    @PostConstruct
    public void postConstruct() {
        redisServer.start();
    }

    @PreDestroy
    public void preDestroy() {
        redisServer.stop();
    }
  
}

和 application.properties 中的嵌入式 Redis 设置:

spring.redis.host=localhost
spring.redis.port=6370

我的 Redis 存储库测试类是:

@ExtendWith(SpringExtension.class)
@DataRedisTest
@Import(TestRedisConfiguration.class)
public class UserRepositoryTest {
    
    @Autowired
    private UserRepository userRepository;
    

    @BeforeEach
    public void setUp() {
        userRepository.deleteAll();
    }


    @Test
    public void saveUser() {

        User user = prepareUser();

        User savedUser = userRepository.save(user);
        User foundUser = userRepository.findById(savedUser.getUserId()).get();
        
        assertThat(foundUser.getEmail()).isEqualTo(savedUser.getEmail());

    }
    

    @Test
    public void findByEmail() {

        User user = prepareUser();

        User savedUser = userRepository.save(user);
        User foundUser = userRepository.findByEmail("[email protected]").get();
        
        assertThat(foundUser.getEmail()).isEqualTo(savedUser.getEmail());

    }
    
    private User prepareUser() {
        
        User user = new User();
        
        user.setUserId("62d322ddf9f5e01864bed242");
        user.setEmail("[email protected]");
        
        return user;
        
    }
}

我还使用测试类检查上下文作为打击:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class MyApiApplicationTest {

    @Test
    void contextLoads() {

    }

}
Redis junit5 自动连线 spring-boot-test spring-repositories

评论


答: 暂无答案