使用Jmockit完成static方法的mock

传统的JMock是无法Mock静态方法的,但是Jmockit能够很好地Mock类的静态方法。

package features.jmockit.staticmock;

public class StaticTarget {

	public static int m1() {
		throw new RuntimeException();
	}

	public static String m2() {
		throw new RuntimeException();
	}

}

我们可以用基于状态和基于行为的方式,对这个类进行mock:

package features.jmockit.staticmock;

import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class RunState {
	@Test
	public void t1() {
		new MockUp() {

			@Mock
			public String m2() {
				return "ATY";
			}

			@Mock
			public int m1() {
				return 100;
			}
		};

		Assert.assertEquals("ATY", StaticTarget.m2());
		Assert.assertEquals(100, StaticTarget.m1());
	}

}

package features.jmockit.staticmock;

import mockit.Deencapsulation;
import mockit.Expectations;
import mockit.integration.junit4.JMockit;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class RunBehaviour {

	@Test
	public void t1() {
		new Expectations(StaticTarget.class) {
			{
				Deencapsulation.invoke(StaticTarget.class, "m1");
				result = 100;

				Deencapsulation.invoke(StaticTarget.class, "m2");
				result = "ATY";
			}
		};

		Assert.assertEquals("ATY", StaticTarget.m2());

		Assert.assertEquals(100, StaticTarget.m1());
	}

}

 

你可能感兴趣的:(单元测试&日志)