Mockito入门学习(记录)

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));
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值