免费ppt模板大全免费下载网站,潜山网站建设,怎么搭建wap网站,泽州网站设计目录 前言1. 单元测试的测试类2. 框架测试的测试类 前言
在实际开发中#xff0c;如果只是做一个简单的单元测试#xff08;不涉及端到端、数据库交互、API调用、消息队列处理等#xff09;#xff0c;我为了方便一般都是找块儿地方写一个main方法来跑一下就行了#xff… 目录 前言1. 单元测试的测试类2. 框架测试的测试类 前言
在实际开发中如果只是做一个简单的单元测试不涉及端到端、数据库交互、API调用、消息队列处理等我为了方便一般都是找块儿地方写一个main方法来跑一下就行了当然不推荐这样做怕被领导发现 。所以还是建议在 /src/test/xxx/ 目录下写一个测试类来做测试。
1. 单元测试的测试类
如果只是为了做一个单元测试比如说测试一个方法是否能正常跑那么可以按照以下流程创建一个 maven依赖 dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.12/versionscopetest/scope/dependency测试类 import org.junit.Test;public class MyTest {Testpublic void test() {long l System.currentTimeMillis();System.out.println(l);}
}要求
测试类中的方法需要加上Test访问修饰符必须是public返回类型必须是void不接受任何参数JUnit5可以用ParameterizedTest来实现参数化测试但是很麻烦可用expected来标注需要捕获的异常Test(expected ExceptionType.class)。
2. 框架测试的测试类
如果需要启动所有上下文进行测试那么在测试类上面加一个SpringBootTest就行了接着就可以使用Bean做测试了如下
SpringBootTest
public class ConfEncTest {Autowiredprivate StringEncryptor jasyptStringEncryptor;Testpublic void encryptTest() {String originPassord 123456;String encryptStr jasyptStringEncryptor.encrypt( originPassord );System.out.println(encryptStr);}}SpringBootTest启动一个全功能的Spring Boot应用上下文来进行集成测试可以使用所有的Bean。启动一个测试方法就相当于启动整个项目比较慢。
如果只是使用几个Bean那么可以使用 RunWith(SpringRunner.class) ContextConfiguration
RunWith(SpringRunner.class)
ContextConfiguration(classes {StringEncryptor.class})
public class ConfEncTest {Autowiredprivate StringEncryptor jasyptStringEncryptor;Testpublic void encryptTest() {String originPassord 123456;String encryptStr jasyptStringEncryptor.encrypt( originPassord );System.out.println(encryptStr);}}RunWith用于指定运行测试类的测试运行器Test Runner需要搭配ContextConfiguration使用。
SpringRunner Spring提供的一个特殊的测试运行器它负责解析SpringBootTest、ContextConfiguration等Spring相关的注解并在测试执行前创建和配置Spring应用上下文。
ContextConfiguration指定包含所需Bean定义的配置类或XML配置文件。这样SpringRunner在运行测试时会根据ContextConfiguration提供的信息来创建一个包含必要Bean的ApplicationContext从而实现对这些依赖的注入。如果需要同时指定多个类可以这样写ContextConfiguration(classes {ConfigA.class, ConfigB.class, ConfigC.class})。
SpringBootTest是一个复合注解其中包含了RunWith。