In F# I want to perform unit testing on a function with several levels of nested functions.
I want to be able to test the nested functions individually as well, but I do not know how I could invoke them.
When debugging, each of these nested functions is invoked as a type of function object, but I don’t know if I can access them at compile time.
I do not want to change the nesting scheme that I am using because it makes the most sense functionally to have them nested this way because there is a de facto “inheritance” of some of the function parameters at each nested level.
Is something like this possible? If not, what is the general procedure for unit testing nested functions? Are they tested individually with extra parameters and then inserted into their nested position afterwords never to be able to be tested again?
Very small example:
let range a b =
let lower = ceil a |> int
let upper = floor b |> int
if lower > upper then
Seq.empty
else
seq{ for i in lower..upper -> i}
How could I test that lower or upper are working properly without changing the nested nature of the code?
I would agree with Daniels comment – if the outer function works correctly, you should not need to test any of the inner functions. Inner functions are really an implementation detail that should not be relevant (especially in functional code, where output does not depend on anything else than inputs). In C#, you also don’t test whether
forloop orwhileloop inside your method works correctly.If both the inner and the outer functions are too complex, then perhaps it would be better to write the inner function as a separate function anyway.
That said, you can, of course, mess with the compiled assembly using reflection and invoke the inner function. Inner functions are compiled as classes with constructor that takes the closure (captured values of the outer function) and
Invokemethod that takes the actual parameters.The following trivial example works, though I have not tested it on anything more realistic: