Reputation: 71
I want to test my code which has a few tail recursive functions.
I couldn't mock the tail recursive functions because they need to declared either Final
or Private
.
Most mocking frameworks don't support mocking such methods, the ones that support isn't working as expected.
Is this possible at all? Can some one provide me their ideas to mock tail recursive functions?
I tried mocking using Mockito
Framework version 3.0.0
. My Test suite is extended with the Mockito-Sugar
trait.
Though mockito documentation suggests that final methods can be mocked, It results in failure for me.
I tried using scala-mock
. I faced different problems and didn't work out.
Upvotes: 0
Views: 224
Reputation: 27356
One way to fix this is to wrap the recursive code in an outer function. For example:
def factorial(n: Int): Int = {
@annotation.tailrec
def loop(i: Int, res: Int): Int =
if (i <= 1) {
res
} else {
loop(i-1, i*res)
}
loop(n-1, n)
}
Using this pattern the factorial
method does not need to be final
or private
so it can be overridden for testing.
Another advantage of this pattern is that the accumulator value res
does not have to be exposed in the main function interface. This pattern also allows special cases to be handled outside the main recursive code, making the inner code simpler and potentially faster.
Upvotes: 5