3

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.

James Dinsdale
  • 789
  • 8
  • 23
  • 3
    According to conventional wisdom, you do not unit-test private methods. – 500 - Internal Server Error Dec 04 '16 at 20:36
  • 2
    @500-InternalServerError care to share some sources to back up this claim? A method's visibility has no bearing on whether or not it's functioning correctly, and the only way to ascertain that it is working is by testing it. To exclude all private methods from testing sounds like a risky strategy. – James Dinsdale Dec 04 '16 at 20:51
  • I heared people say that the class design should be in such a way that there is no need to test private methods, as these are implementaion details. However, this approach (if full test coverage is the goal) then the result will be a class system of very fine granularity, where a lot of delegation is used. – Codor Dec 04 '16 at 21:10
  • http://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones. – 500 - Internal Server Error Dec 04 '16 at 23:01

2 Answers2

2

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)
asterite
  • 2,906
  • 1
  • 14
  • 14
  • 2
    do you really think, that special for tests you should add additional method? You should write tests for cover your code, but not write code for run tests – Oleh Sobchuk Dec 05 '16 at 18:57
  • simply do not use private modifier on any tested method. just like any language with visibility modifiers. Crystal allows to reopen classes, but yes, it's tricky. – Akzhan Abdulin Aug 10 '17 at 23:13
-1

if Crystal ruby-like language than private methods should be tested in public methods. or with code where it uses

Oleh Sobchuk
  • 3,612
  • 2
  • 25
  • 41