Please use the Car application you created for the car assignment as the basis for this exercise.
Also, prepare your project for JUnit tests by adding a “test” folder, marking this as test sources root. Don’t forget to import JUnit (5) to the project.
To start off “simple”, let’s create a few tests which test very basic functionality. For now, we’ll give you a hint on what to do using the method names.
Please implement the following methods:
void createNewCarWithValidLicencePlateGivesNoException()
- which tests that the constructor does not throw an exception if the license plate is valid.void newCarHasFullTank()
- which checks whether or not a newly created car actually has a full tankAnd finally, create some tests that test the driving capability of a car. You may assume that the efficiency of the car is 1:10.
void carWhenDriving50kmConsumes5LiterOfFuel()
void carWithEmptyTankCannotDrive()
For this exercise, we assume your constructor looks like this:
public Car(String licensePlate, double efficiency, int tankSize) { .. }
Looking at this constructor, we see three parts that we need to test. The licensePlate, efficiency and tankSize components each have some rules and restrictions. Let’s focus on each one individually for now..
We already tested something with regards to fuel, but never looked the actual values of tankSize. For now, assume that any negative number is illegal and also 0 is not allowed. Write unit tests to test these two conditions, make sure you name them properly! (Tip: Use the fail()
method.)
Similar to the TankSize, negative or 0 efficiency is also not allowed. Add a fail()
situation for these tests to your test file.
Testing the license plate is a bit more complex, as there are more things that (potentially) could go wrong. Remember that a valid license plate looks like this: 123-ab-4
(so 3 digits, 2 letters, 1 digit, each separated with a -
). This means that we split up these tests into three parts, the first numerical part, the alphabetical part and the final digit.
Write the tests that you think are necessary to test this part of the application!
Please add the following code to your testcase:
class YourTestCase {
private Car testCar;
@BeforeEach
public void createNewCar() {
this.testCar = new Car("000-QR-5", 15.5, 50);
}
}
Rewrite the test that simply use a car to use the testCar
rather
than create one in every test.
Try out various distances, and confirm that the right distance is driven.
Additionally you may confirm that the right amount of fuel is left.