public class UtilTest {
@BeforeClass
public static void initClass(){
System.out.println("i will be called only once,before the first test method");
}
@AfterClass
public static void afterClass(){
System.out.println("i will be called only once,after the last test method");
}
@Before
public void initMethod(){
System.out.println("i will be called before every test method");
}
@After
public void afterMethod(){
System.out.println("i will be called after every test method");
}
@Test
public void testAdd() throws Exception {
Assert.assertEquals(2, add(1,1));
}
@Test(timeout=100)
public void testTimeout(){
try{
Thread.sleep(500);
}catch(InterruptedException e){
}
}
@Test(expected=IndexOutOfBoundsException.class)
public void testException(){
new LinkedList<String>().get(0);
}
@Ignore("ignore the test")
@Test
public void ignoreTest() throws Exception {
Assert.assertEquals(2, add(1,1));
}
public int add(int n1, int n2){
return n1 + n2;
}
}
// Util.java
public class Util{
public static String getEnv(String name){
return System.getenv(name);
}
}
//UtilTest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest({Util.class})//声明要Mock的类
public class UtilTest {
@Test
public void staicMethodMockTest() throws Exception {
PowerMock.mockStatic(System.class);//Mock静态方法
EasyMock.expect(System.getenv("java_home"))).andReturn("env value");//录制Mock对象的静态方法
PowerMock.replayAll();//重放Mock对象
Assert.assertEquals("env value",Util.getEnv("java_home"));
PowerMock.verifyAll();//验证Mock对象
}
}
public class FinalClass {
public final String finalMethod() {
return "final method";
}
}
public class FinalUtil{
public String callFinalMethod(FinalClass cls) {
return cls.getName;
}
}
@RunWith(PowerMockRunner.class)
public class FinalMethodMockTest {
@Test
@PrepareForTest(FinalClass.class)
public void testCallFinalMethod() {
FinalClass cls = PowerMock.createMock(FinalClass.class); //创建Mock对象
FinalUtil util = new FinalUtil();
EasyMock.expect(cls.finalMethod()).andReturn("cls");
PowerMock.replayAll();
Assert.assertTrue(util.callFinalMethod(cls));
PowerMock.verifyAll();
}
}
public class PrivateMockClass
private boolean privateMethod(final String name) {
return true;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(PrivateMockClass.class)
public class PrivatMethodMockTest {
@Test
public void testPrivateMock() throws Exception {
PrivateMockClass mock = PowerMock.createPartialMock(PrivateMockClass.class, “privateMethod”);//只对privateMethod方法Mock
PowerMock.expectPrivate(mock, "privateMethod", "name").andReturn(true);//录制
PowerMock.replay(mock);
assertTrue(mock.privateMethod(“name”));
PowerMock.verify(mock);
}
}