今天在学习springboot结合redis实现二级缓存时,项目依赖引入完成后想要测试redis是否可以连接成功,结果在测试时出现如下错误日志
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:73)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:243)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:155)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:395)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:312)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:265)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:108)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:99)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:139)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:124)
测试用例代码
/**
* redis连接测试
*
* @author 段誉
* @create 2019-04-11 9:27
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RediscacheApplicationTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void contextLoads() {
stringRedisTemplate.opsForValue().set("k1", "v1");
System.out.println(stringRedisTemplate.opsForValue().get("k1"));
}
}
原因
是因为我在搭建好springboot项目后没有创建Application.java
项目启动类导致的
解决办法
创建完Application.java
后,再重新运行测试类正常运行
参考博客
https://blog.csdn.net/weixin_39220472/article/details/80206449