java-Powermock-模拟超级方法调用

这是我的代码-

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

import org.powermock.core.classloader.annotations.*;
import static org.powermock.api.support.SuppressCode.*;

class BaseService {
    public int save() {
        validate();
        return 2;
    }

    public static int save2() {
        return 5;
    }

    public void validate() {
        System.out.println("base service save executing...");
    }
}

class ChildService extends BaseService {
    public int save() {
        System.out.println("child service save executing...");
        int x = super.save2();
        int y = super.save();
        System.out.println("super.save returned " + y);
        load();
        return 1 + x;
    }

    public void load() {
        System.out.println("child service load executing...");
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(BaseService.class)
public class PreventSuperInvocation {

    @Test
    public void testSave() throws Exception {

        org.powermock.api.support.Stubber.stubMethod(BaseService.class,
                "save2", 4);
        suppressMethod(BaseService.class, "save");
        ChildService childService = new ChildService();
        System.out.println(childService.save());
    }

}

我想在ChildService类中模拟super.save().但是我找不到做到这一点的方法. preventMethod()仅禁止并返回默认值(上述情况下为0).诸如MemberModifier,Stubber,MethodProxy之类的东西仅适用于静态方法.

有没有办法在Powermock中做到这一点?

我正在使用Powermock 1.5和Mockito 1.9.5.

解决方法:

看来jMockit可以满足我的需求.也许我可以将这个问题发布到powermock邮件列表中.同时下面就足够了.
包learning_mocking_tools.learning_mocking_tools;
    包learning_mocking_tools.learning_mocking_tools;

import mockit.*;

import org.junit.Assert;
import org.junit.Test;


class BaseService {
    public int save() {
        validate();
        return 2;
    }

    public static int save2() {
        return 5;
    }

    public void validate() {
        System.out.println("base service save executing...");
    }
}

class ChildService extends BaseService {
    public int save() {
        System.out.println("child service save executing...");
        int x = super.save2();
        int y = super.save();
        System.out.println("super.save returned " + y);
        load();
        return 1 + y;
    }

    public void load() {
        System.out.println("child service load executing...");
    }
}

@MockClass(realClass = BaseService.class)
class MockBase {

    @Mock
    public int save() {
        System.out.println("mocked base");
        return 9;
    }
}

public class PreventSuperInvocation {

    @Test
    public void testSave() throws Exception {
        MockBase mockBase = new MockBase();
        Mockit.setUpMock(BaseService.class, mockBase);

        ChildService childService = new ChildService();
//      int x = childService.save();

        Assert.assertEquals(9 + 1, childService.save());

        Mockit.tearDownMocks();
    }

}
上一篇:java-为方法调用的每个实例返回相同的值


下一篇:java-Mockito匹配器以匹配具有泛型和供应商的方法