Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Overview

In this exercise, you will provide unit tests for Account class. The code you'll be working with is hosted in this repository https://github.com/martyus/UnitTestingExercise.git

Task 1 - Set up your project

  1. Create a new IntelliJ project - you can call it UnitTestExercise. Copy and paste the cloned files into your project.

  2. You can run the main method to see how the code works. Explore the class Account.java. Feel free to create more objects.

  3. We will need to add our unit testing dependencies into the project. Download these three jar files:

    1. https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api/5.8.2

    2. https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine/5.8.2

    3. https://mvnrepository.com/artifact/org.junit.platform/junit-platform-commons/1.8.1

...

  • Include the .jar files that you just downloaded.

Task 2 - Create the first test

  1. Create a new Java class - name it AccountTest.java. There is nothing special about this file at this moment.

  2. Create your first test case - let’s focus on the scenario when a customer’s credit score is 0.4. Create a public method that returns void and call it creditScoreTooLowTest.

  3. Annotate this method with @Test decorator. Make sure that it has been imported - at the top of the file you should see import org.junit.jupiter.api.Test;

  4. Within the body of the method, create a new Customer object whose credit score will be set to 0.4. Create a new Account object and pass the customer's reference into the constructor. This is our arrange phase.

  5. Since the interest is calculated when the constructor is called, out arrange phase serves also as the act phase.

  6. Assert phase - we need to check if the calculated interest is what we expect. It should be 1.0 - that’s our expected value. Copy the following line and paste it to the top of your test class : import org.junit.jupiter.api.Assertions;

  7. Call the method assertEquals to check that the expected value matched the actual value - returned from the getInterest() method: Assertions.assertEquals(1.0, account.getInterest() );

  8. Right-click into the AccountTest class and select Run 'AccountTest' . At the bottom of the screen, you should see green ticks meaning your test is passing.

...

Task 2 - Create other tests

  1. Have a look at the Account class and think about the different combinations of the customer's age and credit score to cover all the possible scenarios.

  2. Create the corresponding tests.