当前位置: 代码网 > it编程>编程语言>Java > SpringBoot测试类注入Bean失败的原因及分析

SpringBoot测试类注入Bean失败的原因及分析

2024年09月22日 Java 我要评论
针对springboot的测试类,2.2版本之前和之后是不一样的。2.2版本之后导包pom.xml添加test依赖<!-- starter-test:junit + spring-test +

针对springboot的测试类,2.2版本之前和之后是不一样的。

2.2版本之后

导包pom.xml

添加test依赖

<!-- starter-test:junit + spring-test + mockito -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-test</artifactid>
    <scope>test</scope>
</dependency>

注解

  • @springboottest—import org.springframework.boot.test.context.springboottest;
  • @test—import org.junit.jupiter.api.test;

测试

import org.junit.jupiter.api.test;
import org.springframework.boot.test.context.springboottest;

/**
 * @author wangkanglu
 * @version 1.0
 * @description
 * @date 2024-07-07 11:32
 */
@springboottest
public class testmain {

    @test
    public void test1(){
        system.out.println("-----");
    }
}

2.2版本之前

导包pom.xml

添加test依赖

<!-- starter-test:junit + spring-test + mockito -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-test</artifactid>
    <scope>test</scope>
</dependency>

注解

  • @springboottest—import org.springframework.boot.test.context.springboottest;
  • @runwith(springrunner.class)—import org.junit.runner.runwith;
  • @test—import org.junit.test;

测试

import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.boot.test.context.springboottest;

/**
 * @author wangkanglu
 * @version 1.0
 * @description
 * @date 2024-07-07 11:32
 */
@springboottest
@runwith(springrunner.class)
public class testmain {

    @test
    public void test1(){
        system.out.println("-----");
    }
}

注意包路径需要一致

注意测试类的包名和启动类的包名一定要一致,否则扫描不到bean对象会报空异常,如下图:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com