Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test private methods?

Tags:

crystal-lang

Is there any way of unit testing private methods using Crystal's built-in spec library?

I come from a PHP background, and there it's possible to use ReflectionMethod::setAccessibility to change a method's accessibility to public to allow it to be tested. I can't find anything similiar within the Crystal API docs, so was just wondering if such a thing exists.

like image 675
James Dinsdale Avatar asked Mar 20 '26 12:03

James Dinsdale


1 Answers

I agree that private methods shouldn't be tested. However, if you really want to do it you can reopen the class and redefine the method without any visibility (so public) and use previous_def. For example:

class Foo
  private def bar(x, y)
    x + y
  end
end

# Reopen
class Foo
  # Redefine bar
  def bar(x, y)
    # Invoke the previous definition
    previous_def
  end
end

foo = Foo.new
p foo.bar(1, 2)
like image 82
asterite Avatar answered Mar 25 '26 00:03

asterite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!