JUnit 的基本使用

1.按需导入各种jar包

	//测试覆盖率
	compile group: 'org.jacoco', name: 'jacoco-maven-plugin', version: '0.8.2'
    //基本包
    testCompile "junit:junit:4.12"
    //Spring测试
    testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.17.RELEASE'
    //mock:,powermock是静态方法的mock
    testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.4'
    testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.7.4'
    testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
    //grpc测试
    testCompile group: 'io.grpc', name: 'grpc-testing', version: '1.15.0'

2.对JUnit的理解:
JUnit提供了一个很方便的测试环境

	建立一个待测试的模版
    public int add(int a, int b) {
        return a+b;
    }

    public int addPlus(int a, int b) {

        int ans = add(a, b) + 10;

        return ans;
    }

    public int addYou(int a, int b) {

        int ans = add(a, b);
        ans += YouMath.addLow();
        return ans;
    }

	//测试,加上一个@Test 就可以不需要main方法进行测试
@Test
    public void addPlusTest() {

		//模拟MyMath方法,架空这个类
        MyMath mock = Mockito.mock(MyMath.class);
		//模拟MyMath方法,在需要的时候模拟方法
        //MyMath spy = Mockito.spy(MyMath.class);
        Mockito.doReturn(9).when(mock).add(1, 2);
        int ans = mock.addPlus(1, 2);
        System.out.println(ans);
    }

    @Test
    public void addYoutest() throws Exception{
        MyMath math = new MyMath();
        //mock一个静态方法,不需要导入测试环境就可以测试
        PowerMockito.mockStatic(YouMath.class);
        PowerMockito.doReturn(0).when(YouMath.class, "addLow");
        int ans = math.addYou(1, 2);
        System.out.println(ans);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值