Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you test nested functions in scala?

Is there any way to test a nested function (ideally with ScalaTest)?

For example, is there a way to test g() in the below code:

def f() = {
  def g() = "a string!"
  g() + "– says g"
}
like image 348
Aaron Yodaiken Avatar asked Mar 17 '11 00:03

Aaron Yodaiken


People also ask

What is nested function in Scala?

A function definition inside an another function is known as Nested Function. It is not supported by C++, Java, etc. In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions .

Can we call a function inside a function in Scala?

In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions .

What is a nested function in Python?

This concept of defining a function in the definition of another is called Nesting. Like any other code block, a nested function can also be used to define multiple code definitions inside a function. The nested function makes it easier to detect the code and increases modularity.

Can you implement a factorial calculator with nested functions?

Here is an implementation of a factorial calculator, where we use a conventional technique of calling a second, nested method to do the work. Try the following program to implement nested functions.


1 Answers

g is not visible outside of f, so I daresay no, at least not without reflection.

I think testing g would break the concept of unit testing, anyway, because you should never test implementation details but only public API behaviour. Tracking an error to a mistake in g is part of the debugging process if tests for f fail.

If testing g is important for you, define g as (protected) method outside of f. That might break your design, though.

Another idea would be to put calls to assert after the call of g in the original code. This will be executed during tests and raise an exception if the property does not hold, causing the test to fail. It will be there in regular code, too, but can be removed by the compiler as assert (and companions) are elidible (see e.g. here).

like image 109
Raphael Avatar answered Sep 28 '22 12:09

Raphael