What's the best way to unit test protected & private methods in Ruby?

后端 未结 16 624
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 10:47

What\'s the best way to unit test protected and private methods in Ruby, using the standard Ruby Test::Unit framework?

I\'m sure somebody will pipe up a

16条回答
  •  猫巷女王i
    2020-12-12 11:36

    I would probably lean toward using instance_eval(). Before I knew about instance_eval(), however, I would create a derived class in my unit test file. I would then set the private method(s) to be public.

    In the example below, the build_year_range method is private in the PublicationSearch::ISIQuery class. Deriving a new class just for testing purposes allows me to set a method(s) to be public and, therefore, directly testable. Likewise, the derived class exposes an instance variable called 'result' that was previously not exposed.

    # A derived class useful for testing.
    class MockISIQuery < PublicationSearch::ISIQuery
        attr_accessor :result
        public :build_year_range
    end
    

    In my unit test I have a test case which instantiates the MockISIQuery class and directly tests the build_year_range() method.

提交回复
热议问题