Sometimes we may wish to write a set of generic tests and then reuse them for specific inputs. In Kotest we can do this via test factories which create tests that can be included into one or more specs.
Say we wanted to build our own collections library. A slightly trite example, but one that serves the documentation purpose well.
We could create an interface
IndexedSeq which has two implementations,
If we wanted to test our
List implementation, we could do this:
Now, if we wanted to test
Vector we have to copy n paste the test. As we add more implementations and more tests, the likelihood is our test suite will become fragmented and out of sync.
We can address this by creating a test factory, which accepts an
IndexedSeq as a parameter.
To create a test factory, we use a builder function such as
wordSpec and so on. A builder function exists for each of the spec styles.
So, to convert our previous tests to a test factory, we simply do the following:
And then to use this, we must include it one or more times into a spec (or several specs).
You can include any style factory into any style spec. For example, a fun spec factory can be included into a string spec class.
A test class can include several different types of factory, as well as inline tests as normal. For example:
Each included test appears in the test output and reports as if it was individually defined.
Tests from factories are included in the order they are defined in the spec class.
Test factories support the usual before and after test callbacks. Any callback added to a factory, will in turn be added to the spec or specs where the factory is included.
However, only those tests generated by that factory will have the callback applied. This means you can create stand alone factories with their own lifecycle methods and be assured they won't clash with lifecycle methods defined in other factories or specs themselves.
After executing the test suite, the following would be printed:
And as you can see, the
beforeTest block added to
factory1 only applies to those tests defined in that factory, and not in the tests defined in the spec it was added to.