Mockito入门
学习自bilibili 搞钱小王
https://www.bilibili.com/video/BV15S4y1F7Xr?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=818c5319e73eab4ccc27c72846438d6e
配上一张图
导入依赖
导入两个依赖,我是用的gradle,各位也可以用maven
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
testImplementation 'org.mockito:mockito-core:4.3.1'
}
测试方法
verify
用来验证代码是否执行过
mockito用类似代理的作用代理random(这种方式的话,如果有操作数据库,前台之类会改动的地方,就不会去真的改动),之后执行random的nextInt方法,用verify方法来验证
@Test
void add() {
Random random = Mockito.mock(Random.class);
random.nextInt();
Mockito.verify(random).nextInt();
}
还可以来测试执行次数
@Test
void add() {
Random random = Mockito.mock(Random.class);
System.out.println(random.nextInt());
System.out.println(random.nextInt());
//Mockito.verify(random).nextInt();
Mockito.verify(random,Mockito.times(2)).nextInt();
}
when
打桩断言
设置random的返回值为100,然后用Assertions去验证是否相等
@Test
void add() {
Random random = Mockito.mock(Random.class);
Mockito.when(random.nextInt()).thenReturn(100);
Assertions.assertEquals(1020,random.nextInt());
}
thenThrow和thenCallRealMethod
thenThrow是断言时让其抛出异常
Mockito.when(mockitoTest.add(1,2)).thenThrow(new RuntimeException());
thenCallRealMethod是让其使用真实方法(和spy注解类似)
Mockito.when(mockitoTest.add(1,2)).thenCallRealMethod();
注解
mock
mock需要搭配MockitAnnotations.openMocks(testClass)方法一起使用
这个和刚刚上面那个是一样的
@Mock
private Random random;
//这个就相当于 Random random = Mockito.mock(Random.class);
@Test
void add() {
MockitoAnnotations.openMocks(this);
Mockito.when(random.nextInt()).thenReturn(100);
Assertions.assertEquals(1020,random.nextInt());
}
MockitoTest类中如果有静态方法,就用如下方式调用
Mockito.mockStatic(MockitoTest.class);
@BeforeEach和@AfterEach
测试前操作和测试后操作
@BeforeEach
void before(){
System.out.println("测试前准备");
}
@Test
void add() {
MockitoAnnotations.openMocks(this);
Mockito.when(random.nextInt()).thenReturn(100);
Assertions.assertEquals(100,random.nextInt());
}
@AfterEach
void after(){
System.out.println("测试后收尾");
}
@spy
spy走的是真实方法,和mock相反
@Spy
private MockitoTest mockitoTest;
@BeforeEach
void before(){
MockitoAnnotations.openMocks(this);
}
@Test
void add() {
Assertions.assertEquals(2,mockitoTest.add(1,2));
}
最后
以上就是自然戒指最近收集整理的关于Mockito入门学习(记录)Mockito入门的全部内容,更多相关Mockito入门学习(记录)Mockito入门内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复