【问题标题】:Wanted: Most elegant way to code an anonymous class for mocking通缉:编写用于模拟的匿名类的最优雅方式
【发布时间】:2014-02-03 20:22:01
【问题描述】:

我在为我的测试模拟部分 Net::SFTP。以下通过从fixture_path 本地读取来模仿dir.entriesentry.nameentry.attributes.size

class MockedSFTP
  mattr_accessor :fixture_path
  def dir
    Class.new do
      def entries(path)
        MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
          OpenStruct.new(
            name: child.basename,
            attributes: OpenStruct.new(size: child.size)
          )
        end
      end
    end.new
  end
end

另一种选择是:

class MockedSFTP
  mattr_accessor :fixture_path
  def dir
    object = Object.new
    def object.entries(path)
      MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
        OpenStruct.new(
          name: child.basename,
          attributes: OpenStruct.new(size: child.size)
        )
      end
    end
    object
  end
end

两个版本都工作得很好,但是,我都不喜欢它们。 Class.new do ... end.new 很丑,我根本不喜欢 object = Object.new; ...; object 代码。

有没有第三种写法?

【问题讨论】:

    标签: ruby mocking minitest


    【解决方案1】:

    实际声明类怎么样?

    class MockedSFTP
    
      mattr_accessor :fixture_path
    
      class Dir
        def entries(path)
          MockedSFTP.fixture_path.join(path.sub(%r{^/}, '')).children.map do |child|
            OpenStruct.new(
              name: child.basename,
              attributes: OpenStruct.new(size: child.size)
            )
          end
        end
      end
    
      def dir
        Dir.new
      end
    end
    

    【讨论】:

    • 那是我的第一个镜头,但它更加冗长。我一直在寻找一种更“匿名”的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多