gpt4 book ai didi

java - 如何模拟私有(private)静态属性,特别是 ResourceBundle

转载 作者:行者123 更新时间:2023-12-05 07:02:45 24 4
gpt4 key购买 nike

我想模拟缺少 message.properties 的情况。

public class ClassToTest{
private static ResourceBundle bundle = ResourceBundle.getBundle("message");
public static String getMessage(String key){
return bundle.getString(key);
}
}

但是当我尝试时:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ResourceBundle.class)
public class ClassToTestTest{

@Test
public void myTest(){
PowerMockito.spy(ResourceBundle.class);
PowerMockito.when(ResourceBundle.class, "getBundle").thenThrow(new Exception("missing message.properties"));
}

}

我也尝试过其他方法,但我总是得到 NoClassDefFoundError:org/mockito/exceptions/Reporter

最佳答案

我会选择以下内容(注意 - 模拟静态方法需要 Mockito 3.4.x)

public class ClassToTestTest {
@Test
public void test() {
try (MockedStatic<ResourceBundle> dummyStatic = Mockito.mockStatic(ResourceBundle.class)) {
dummyStatic.when(() -> ResourceBundle.getBundle(anyString()))
.thenThrow(new MissingResourceException("s", "className", "key"));
// when
try {
var underTest = new ClassToTest();
} catch (ExceptionInInitializerError ex) {
var cause = ex.getCause();
Assertions.assertEquals(MissingResourceException.class, cause);
}
}
}
}

与 PowerMock 相同的测试:

import org.junit.Assert;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.Test;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToTest.class})
public class ClassToTestTest {
@Test
public void myTest() {
var exMessage = "m1";
try {
PowerMockito.mockStatic(ResourceBundle.class);
PowerMockito.when(ResourceBundle.getBundle("message"))
.thenThrow(new MissingResourceException(exMessage, "className", "key"));
var underTest = new ClassToTest();
} catch (ExceptionInInitializerError ex) {
Assert.assertEquals(MissingResourceException.class, ex.getCause().getClass());
Assert.assertEquals(exMessage, ex.getCause().getMessage());
}
}
}

关于java - 如何模拟私有(private)静态属性,特别是 ResourceBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63446110/

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