单身和单元测试 [英] Singleton and unit testing

查看:119
本文介绍了单身和单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Effective Java在单元测试单例上有以下声明

The Effective Java has the following statement on unit testing singletons


使类成为单例可能会使其难以测试其客户端,因为除非它实现了作为其类型的接口,否则不可能将模拟实现替换为单例。

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.

任何人都可以解释为什么是这样吗?

Can anyone explain the why this is so ?

推荐答案

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

You could use reflection to reset your singleton object to prevent tests from affecting each other.

@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

这篇关于单身和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆