1. 程式人生 > >Partial mock local private method or public method in the class and suppress static initial block

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

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();
		}
	}
}