gpt4 book ai didi

java - PowerMock:模拟仅影响一次测试的静态方法

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

我的情况:

我想添加一个新的测试。我需要模拟 Service 类的一个静态方法 X。不幸的是,现有的测试正在以某种方式使用这种静态方法。

当我使用 PowerMock 模拟 X 方法时,其他测试失败了。更重要的是我不应该接触其他测试。

是否有机会仅针对一次测试模拟静态方法? (使用 PowerMock)。

提前致谢。

最佳答案

当然,这是可能的!唯一可能遇到问题的情况是您尝试同时测试多个线程……我在下面举了一个如何执行此操作的示例。享受吧。

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.modules.junit4.PowerMockRunner;

import static org.easymock.EasyMock.*;

import static org.junit.Assert.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(IdGenerator.class)
public class TestClass {

@Test
public void yourTest()
{
ServiceRegistrator serTestObj = new ServiceRegistrator();

PowerMock.mockStatic(IdGenerator.class);
expect(IdGenerator.generateNewId()).andReturn(42L);
PowerMock.replay(IdGenerator.class);
long actualId = IdGenerator.generateNewId();

PowerMock.verify(IdGenerator.class);
assertEquals(42L,actualId);
}

@Test
public void unaffectedTest() {
long actualId = IdGenerator.generateNewId();

PowerMock.verify(IdGenerator.class);
assertEquals(3L,actualId);
}
}

测试类

public class IdGenerator {
public static long generateNewId()
{
return 3L;
}
}

关于java - PowerMock:模拟仅影响一次测试的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223411/

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