Partial mock local private method or public method in the class and suppress static initial block

本文介绍了一个简单的Java计算器类实现及使用PowerMock框架进行私有方法和公共方法的单元测试过程。该计算器类包括加法和减法两个基本运算,并通过模拟测试验证了这些功能的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Calc {
	static {
		System.out.println("hahaha");
	}

	public int add(int a, int b) {
		return interADD(a, b);
	}

	private int interADD(int a, int b) {
		return a + b;
	}

	public int minus(int a, int b) {
		return interMinus(a, b);
	}
	
	public int interMinus(int a, int b) {
		return a-b;
	}
}

package com.kevin.util;

import static org.junit.Assert.*;
import junit.framework.Assert;

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calc.class})
//suppress static initial
@SuppressStaticInitializationFor({"Calc.class"})
public class CalcTest {

	//mock private method in class that be testing
	@Test
	public void testAdd() {
		Calc createPartialMock = PowerMock.createPartialMock(Calc.class, "interADD");
		try {
			PowerMock.expectPrivate(createPartialMock, "interADD",2,3).andReturn(1000);
			PowerMock.replay(createPartialMock);
			int result = createPartialMock.add(2, 3);
			Assert.assertEquals(1000, result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			fail();
		}
	}
	
	//mock public method int class that be testing
	@Test
	public void testMinus() {
		Calc createPartialMock = PowerMock.createPartialMock(Calc.class, "interMinus");
		try {
			EasyMock.expect(createPartialMock.interMinus(5, 4)).andReturn(1000);
			EasyMock.replay(createPartialMock);
			int result = createPartialMock.minus(5, 4);
			Assert.assertEquals(1000, result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			fail();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值