欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > SpringBoot整合junit

SpringBoot整合junit

2025/2/22 16:43:24 来源:https://blog.csdn.net/weixin_65866298/article/details/145242230  浏览:    关键词:SpringBoot整合junit

SpringBoot 整合 junit 特别简单,分为以下三步完成:

1在测试类上添加 @SpringBootTest 注解
2使用 @Autowired 注入要测试的资源
3定义测试方法进行测试

1.实验准备: 

创建一个名为 springboot_junit_test 的 SpringBoot 工程,工程目录结构如下

在 com.example.service 下创建 BookService 接口,内容如下 

public interface BookService {public void save();
}

在 com.example.service.impl 包写创建一个 BookServiceImpl 类,使其实现 BookService 接口,内容如下

@Service
public class BookServiceImpl implements BookService {@Overridepublic void save() {System.out.println("service is running!");}
}

2.编写测试类 

在 test/java 下创建 com.example 包,在该包下创建测试类,将 BookService 注入到该测试类中 

@SpringBootTest
class SpringbootJunitTestApplicationTests {@Autowiredpublic BookService bookService;@Testvoid contextLoads() {bookService.save();}}

注意:这里的引导类所在包必须是测试类所在包及其子包。

例如:

        引导类所在包是 com.example

        测试类所在包是 com.example

 如果不满足这个要求的话,就需要在使用 @SpringBootTest 注解时,使用 classes 属性指定引导类的字节码对象。如

@SpringBootTest(classes = SpringbootJunitTestApplicationTests.class

3.运行测试方法 

整合成功! 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词