栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mockito之:Spy

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mockito之:Spy

Mockito之:Spy 被测试方法
package com.newcrud.learn;

import lombok.Data;

@Data
public class MySpy {
    int a=100;
    public void fun(){
        System.out.println("fun");
        funOne();
        funTwo();
    }
    public void funOne(){
        System.out.println("funOne");
    }
    public void funTwo(){
        System.out.println("funTwo");
    }
    public Integer getMath(){
        return a;
    }
}
测试类
package com.newcrud.learn;

import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.Mockito.when;
import static org.testng.Assert.*;

@SpringBootTest
public class MySpyTest extends AbstractTestNGSpringContextTests {
    @Spy
    MySpy mySpy;
    @BeforeClass
    public void initMocks(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFun() {
        mySpy.fun();
        System.out.println("=======");
    }

    @Test
    public void testFunOne() {
        mySpy.funOne();
        System.out.println("=======");

    }

    @Test
    public void testFunTwo() {
        mySpy.funTwo();
        System.out.println("=======");

    }

    @Test
    public void testGetMath() {
        System.out.println(mySpy.getMath());
    }
    @Test
    public void testGetMathTwo(){
        when(mySpy.getMath()).thenReturn(200);
        System.out.println(mySpy.getMath());
    }

}

结果

fun
funOne
funTwo
=======
funOne
=======
funTwo
=======
100
200
结论

1、Mock声明的对象,对函数的调用均执行mock(即虚假函数),不执行真正部分。

2、Spy声明的对象,对函数的调用均执行真正部分。

3、相对于@Mock(answer = Answers.CALLS_REAL_METHODS),更推荐@Spy

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337081.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号