springboot项目创建Test包且解决java.lang.IllegalStateException: Failed to load ApplicationContext问题

avatar
作者
筋斗云
阅读量:0

项目不带Test包就得自己搞一个

pom.xml添加依赖

<dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-test</artifactId>     <scope>test</scope> </dependency>

创建目录(src下跟main同级且要跟启动类同路径结构)

编写代码

@RunWith(SpringRunner.class) //如果此文件所在目录跟启动类所在目录不一致就要加上classes = FirmwareApplication.class //webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT是解决找不到spring上下文对象 @SpringBootTest(classes = FirmwareApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class Mytest {      @Autowired     private FirmwareServiceImpl firmwareServiceImpl;      @Test     public void hello(){         List<HashMap<Integer,String>> integerStringHashMap = firmwareServiceImpl.firmwareTypeRanking();         System.out.println(integerStringHashMap);     }  } 

如果不加webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT就会出现下图报错java.lang.IllegalStateException: Failed to load ApplicationContext

不加@RunWith(SpringRunner.class)就会出现

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!