要测试Spring Data Redis,您可以使用以下方法:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</-------->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties
或application.yml
文件中配置Redis连接信息。spring.redis.host=localhost
spring.redis.port=6379
或
spring:
redis:
host: localhost
port: 6379
JpaRepository
的接口,用于操作Redis数据。import org.springframework.data.redis.repository.RedisRepository;
import java.util.concurrent.TimeUnit;
public interface MyRedisRepository extends RedisRepository<String, String> {
String getValue(String key);
void setValue(String key, String value, long expiration, TimeUnit timeUnit);
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.redis.DataJpaTest;
@DataJpaTest
public class MyRedisRepositoryTest {
@Autowired
private MyRedisRepository myRedisRepository;
@Test
public void testSetValueAndGetValue() {
String key = "testKey";
String value = "testValue";
long expiration = 60; // 1 minute
TimeUnit timeUnit = TimeUnit.SECONDS;
myRedisRepository.setValue(key, value, expiration, timeUnit);
String retrievedValue = myRedisRepository.getValue(key);
assert retrievedValue != null && retrievedValue.equals(value);
}
}
注意:在实际项目中,您可能需要根据实际需求调整Redis的配置、接口定义和测试用例。