Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration

在跟着B站瑞吉外卖实战项目学习Spring Data Redis时,启动redis测试代码一直报错:

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

跟着视频一起敲的代码,但就是跑不起来

package com.itheima;

import com.itheima.reggie.ReggieApplication;
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;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testString() {
        redisTemplate.opsForValue().set("city" , "北京");
        Object city = redisTemplate.opsForValue().get("city");
        System.out.println(city);
    }
}

后面查资料发现原因在于:测试方法在运行的时候,需要寻找到SpringBoot启动类,默认情况下会直接在当前包路径上寻找
而我的项目结构是这样的:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration_第1张图片
所以需要在@SpringBootTest注解加上SpringBoot的启动类classes = ReggieApplication.class
修改后的代码:

package com.itheima;

import com.itheima.reggie.ReggieApplication;
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;

@SpringBootTest(classes = ReggieApplication.class)
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testString() {
        redisTemplate.opsForValue().set("city" , "北京");
        Object city = redisTemplate.opsForValue().get("city");
        System.out.println(city);

    }

}

你可能感兴趣的:(java,spring,boot,后端,java,redis)