I'm trying to write unit test for Redis repository of my spring boot application. But the autowired repository object causes the exception below when I run the test case:
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 annotation should autowire the repository object, but it doesn't. What is wrong or missing? Any help would be appreciated.
Spring boot version : 2.6.6
I use embedded Redis for testing. My maven dependency is:
<dependency>
<groupId>it.ozimov</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.7.2</version>
<scope>test</scope>
</dependency>
My Embedded Redis configuration class is:
@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();
}
}
And Embedded Redis settings at application.properties:
spring.redis.host=localhost
spring.redis.port=6370
My Redis repository test class is:
@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;
}
}
I also check the context with a test class as blow:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class MyApiApplicationTest {
@Test
void contextLoads() {
}
}