Leave a rating/review
Notice how each test starts with the same statement, we create a question and then proceed to make assertions with the question that we created.
Val question equals question, val question equals question and the same over and over again: val question = question, val question = question.
This makes your tests very long with code that repeats itself over and over again. To improve this JUnit has the @Before annotation that helps us create a method that will be executed before all the tests are run. We are going to use it now. We will get rid of this line in all of our tests, it is almost magical.
@Before
fun setup() {
val question = Question("CORRECT", "INCORRECT")
}
And the we are going to create a lateinit var to hold that question object.
private lateinit var question: Question
Now we can get rid of this line of code in all of our methods.
Then execute all of your tests again to make sure that they all pass. Amazing!
JUnit provides other annotations that may be helpful to you. For example the @After annotation which makes a method execute after each one of your tests. You can use it to reset any of your objects or tear down anything that you want.
You also have the @Before annotation, if you annotate a method with this it will be executed only once before all the tests are executed. This is helpful if you want to open a file or open a connection to a database or something like that.
And just like you have the @BeforeClass you have the @AfterClass and you use this to annotate a method that will be executed onlye one after all your tests are executed. This is helpful to close a file or to close a connection to a database.
Amazing!