gpt4 book ai didi

java - 单例和单元测试

转载 作者:IT老高 更新时间:2023-10-28 20:53:01 25 4
gpt4 key购买 nike

Effective Java 有以下关于单元测试单例的声明

Making a class a singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.

谁能解释为什么会这样?

最佳答案

您可以使用反射来重置您的单例对象,以防止测试相互影响。

@Before
public void resetSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field instance = MySingleton.class.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null, null);
}

引用:unit-testing-singletons

关于java - 单例和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8256989/

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