我在项目的测试包里面写了测试方法,然后注入RedisTemplate,发现redisTemplate爆红,提示找不到bean。首先说下我犯得错误。
1、
这是主要的原因,没有加@RunWith(SpringRunner.class)注解
然后我的@SpringBootTest还要在后面指定上classes = Application.class,这是因为我的main启动的包名和Test的包名不一致导致的。
spring boot测试类包名与main下application.class启动类的包名默认要一致
这个bug相对于踩了两坑,还是SpringBoot不熟练
package com.ccl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author 超厉害的我啊
* @date 2021/3/23 10:46:09
*/
@RunWith(SpringRunner.class)
//@SpringBootTest(classes = Application.class)
@SpringBootTest
public class ApplicationTest {
@Autowired
private RedisTemplate redisTemplate;
// @Resource
// RedisTemplate redisTemplate;
@Test
public void contextLoads(){
//redisTemplate 操作不同的数据类型,ops和redis的指令是一样的
//opsForValue 操作字符串 类似String
//opsForList 操作List 类似List
//opsForHash
//.....
redisTemplate.opsForHash();
redisTemplate.opsForValue();
//除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务,和基本的CRUD
//获取redis的连接对象
// RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
// connection.flushAll();
// connection.flushDb();
redisTemplate.opsForValue().set("mykey","ccl");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
}