如何使用junit模拟调用单例类的类
我想测试 class1
中调用单例类 getInstance
的方法:
Class ivDomain {
public String method1() {
id=Singleton.getInstance().generateId()
... code
}
}
当我使用 Junit 进行测试时,我收到 NullPointerException
单例类。我该如何解决这个问题?
I would like to test a method from class1
which calls the singleton class getInstance
:
Class ivDomain {
public String method1() {
id=Singleton.getInstance().generateId()
... code
}
}
When I do the test using Junit I am getting NullPointerException
on the singleton class. How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用静态访问单例的类测试起来很痛苦。更改您的 ivDomain 类,以将单例实例作为其构造函数的参数,然后正常模拟它。您应该使用依赖注入框架(例如 Guice)来制作这种样式的发展更加容易。
Classes using statically accessed singletons are a pain to test. Change you ivDomain class to rather take the singleton instance as a parameter to it's constructor and then mock it normally. You should use a Dependency Injection framework (such as Guice) going forward to make this style of development easier.
你不应该嘲笑 Singleton;只需更改代码,使
getInstance()
不会返回 null。You shouldn't have to mock Singleton; just change the code so
getInstance()
doesn't return a null.最可能的原因 - 没有检查您的单例代码 - 是它的初始化无法加载某些外部配置,因此失败。
自动单元测试中的单例可能是一个问题,因为有时您希望它们针对您测试的特定场景表现不同(例如,您希望在一个场景中
generateId
返回 -1,在另一个场景中返回 4354353,在另一个场景中返回 4354353它会抛出一个 RuntimeException - 这样您就可以看到使用单例的代码是如何工作的。在这种情况下,建议更改设计,因为单例不属于受欢迎的设计模式,并且在某种程度上被认为是反的。 - 模式。The most likely reason - without examining your Singleton's code - is that it's initialization fails to load some external configuration and therefore fails.
Singletons in Automatic Unit Tests can be a problem since sometimes you like them to behave differently for the specific scenario you test (e.g. you want one scenario where
generateId
returns -1, another when it returns 4354353 and another when it throws aRuntimeException
- just so you can see how the code that uses the Singleton works. In such cases a change of design is recommended as Singletons are not amongst the favored design patterns and are somewhat regarded as anti-patterns.查看
模拟单例类
check
mocking a singleton class