要測試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的配置、接口定義和測試用例。