06 - Unit Testing - Exercise
Overview
In this exercise, you will provide unit tests for Account
class. The code you'll be working with is hosted in this repository GitHub - martyus/UnitTestingExercise
Task 1 - Set up your project
Create a new IntelliJ project - you can call it
UnitTestExercise
. Copy and paste the cloned files into your project.You can run the main method to see how the code works. Explore the class
Account.java
. Feel free to create more objects.We will need to add our unit testing dependencies into the project. Download these three jar files:
Back in IntelliJ, right click On your project and select
Open Module Settings
Make sure that the
Modules
tab on the left hand side is selected. SelectDependencies
tab in the middle part of the window and look for the+
sign. Click the+
button and click the first option -JARs or Directories
.
Include the
.jar
files that you just downloaded.
Task 2 - Create the first test
Create a new Java class - name it
AccountTest.java
. There is nothing special about this file at this moment.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 returnsvoid
and call itcreditScoreTooLowTest
.Annotate this method with
@Test
decorator. Make sure that it has been imported - at the top of the file you should seeimport org.junit.jupiter.api.Test;
Within the body of the method, create a new
Customer
object whose credit score will be set to 0.4. Create a newAccount
object and pass the customer's reference into the constructor. This is our arrange phase.Since the interest is calculated when the constructor is called, out arrange phase serves also as the act phase.
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;
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() );
Right-click into the
AccountTest
class and selectRun 'AccountTest'
. At the bottom of the screen, you should see green ticks meaning your test is passing.
Task 2 - Create other tests
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.Create the corresponding tests.