gpt4 book ai didi

java - Powermock - 模拟 super 方法调用

转载 作者:搜寻专家 更新时间:2023-11-01 03:54:04 25 4
gpt4 key购买 nike

这是我的代码-

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()。但我找不到办法。 suppressMethod() 仅抑制并返回默认值(在上述情况下为 0)。 MemberModifierStubberMethodProxy 等内容仅适用于静态方法。

在 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 - Powermock - 模拟 super 方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com