本文介绍了是否可以在不调用 initialize 的情况下实例化 Ruby 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,当我编写单元测试时,我需要在不调用 initialize 方法的情况下实例化一个类.例如,当构造函数实例化其他类时,无论如何我都会用存根替换这些类.例如:

Some times when I write unit tests I need to instantiate a class without the initialize method being invoked. For instance when the constructor instantiates other classes that I will replace with stubs anyway. For instance:

class SomeClassThatIWillTest
  def initialize
    @client = GoogleAnalyticsClient.new
    @cache = SuperAdvancedCacheSystem.new
  end

  # ...
end

在测试中,我可能会将 @client@cache 替换为存根,因此我宁愿从未调用构造函数.有什么黑魔法可以帮助我解决这个问题吗?

In a test I will probably replace both @client and @cache with stubs, so I'd rather the constructor was never invoked. Is there any black magic that can help me out with that?

推荐答案

当然可以.Class#new 只不过是一种方便的方法,它使您不必手动分配和初始化对象.它的实现大致如下:

Sure you can. Class#new is nothing more than a convenience method that saves you from having to allocate and initialize an object manually. Its implementation looks roughly like this:

class Class
  def new(*args, **kwargs, &blk)
    obj = allocate
    obj.send(:initialize, *args, **kwargs, &blk)
    obj
  end
end

你可以手动调用Class#allocate,而不是调用initialize.

You can just call Class#allocate manually instead, and not call initialize.

这篇关于是否可以在不调用 initialize 的情况下实例化 Ruby 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 00:46