To test the Donut class, we’d first need to create a test file. In the project’s directory, we have three folders with the same package name; each package has a different use. We’ll create a DonutTest class under the package that has (test) following the package name. This is where we make all the test classes for unit tests. We’ll name our test class DonutTest, and initialize an instance of the Donut. Junit provides its lifecycle annotations to help us create well-managed tests.
Initializations in the JUnit framework usually take place in functions annotated with @BeforeAll or @BeforeEach. Test functions marked with @BeforeAll run first when we run out test class and are only called once, whereas methods with @BeforeEach annotations are called before each test. Since we need to create a Donut object only once, I’ll go ahead and put that in the function annotated with @BeforeAll. We could also initialize objects in a @BeforeEach function if there’s a logic that needs to be tested for a new instance of the class. In case you choose to add your initializations in @BeforeAll function, you’d need to change the declaration of the function to be static. Since Kotlin doesn’t have a static function as we use in Java, we’d need to annotate our test class with @TestInstance(TestInstance.Lifecycle.PER_CLASS).