项目场景:
使用idea进行测试SpringBoot的项目
问题描述
使用idea进行项目测试的时候,报这个错误
Test ignored. java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
原因分析:
测试类在运行时找不到启动类,所以报错
解决方案:
1.检查项目中的启动类是否存在,如果没有赶紧补上。
正确的启动类示例代码如下:
package com.jsbiot;
import cn.hutool.extra.spring.EnableSpringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = {"com.jsb.iot.common.handle", "com.jsbiot"})
@EnableSpringUtil
public class JsbiotApplication {
public static void main(String[] args) {
SpringApplication.run(JsbiotApplication.class, args);
}
}
位置如下
2.启动类存在,但是测试类所在的包与启动类所在的包不在同一级目录下。
如图所示,在和启动类一样的目录下
如果不想写,可以加上以下的SpringBootTest注解,
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {JsbiotApplication.class})
public class JwtTest {
@Autowired
private JwtUtils jwtUtils;
@Test
public void test() {
String token = jwtUtils.generateToken(1);
System.out.println(token);
}
}
二者选其一即可,效果等同。