Test-Driven Development in Android

Jan 24 2023 · Kotlin 1.6, Android 12, AS Bumblebee 2021.1.1

Part 1: Unit Tests

09. Refactor JUnit Tests

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 08. Answer Question Tests Next episode: 10. Build Integration Tests

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 09. Refactor JUnit Tests

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!