What is memoized in Spek?

984 views Asked by At

Spek documentation references

As a best practice you typically want test values to be unique for each test this can be done by using a lateinit variable and assigning it within a beforeEachTest. lateinit var calculator: Calculator

beforeEachTest {
    calculator = Calculator()
}

To make it more concise, Spek provides memoized to do the same thing:


val calculator by memoized { Calculator() }

What exactly is memoized?

1

There are 1 answers

0
Yoni Gibbs On BEST ANSWER

Memoization is remembering (caching) the result of a function call with a given set of parameter values so that if that same function is called again with the same parameter values, the cached result will be returned rather than having to re-run the function. It's an optimisation technique.

See more info here: https://en.wikipedia.org/wiki/Memoization

So in the example above Spek wraps the call to construct a Calculator in its memoized function, meaning that it will only construct it once, and thereafter calls to calculator will re-use that existing instance. And in terms of how you'd generally use it in a test, that would give you the same behaviour as constructing a new Calculator in beforeEachTest, but in a more concise way.