I’ve decided that I wanted to practice making more JUnit tests. I did well on my last homework assignment, but I feel like I still need more practice. It took me some time to do it. I may have to generate my own JUnit tests in the midterm so I would need to make them at a faster rate. Anyway, practice makes perfect so there is no such thing as too much practice.
For this post I will be using this website: Inheritance in Java – GeeksforGeeks
This website contains two examples of code but I will use the first one. The code does not allow for user input but I’ll be drafting tests as if it does.
Before I write any test I would write:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
They will be useful later.
The first test I would make is a constructor test. I believe it should be one of the first tests. It is good to know the test works as it is supposed to since if it cannot do that it will need to be immediately revised. So, I would do this:
@Test
public void testMountainBikeConstructor() {
MountainBike mb = new MountainBike(30, 10, 45);
assertEquals(30, mb.gear);
assertEquals(10, mb.speed);
assertEquals(45, mb.seatHeight);
}
This is supposed to be take in three values and tests if the constructor initializes them correctly. I used the name “mb” because it was already in a class that was used to test inputs. It just made sense to me.
Another test I created tests the set string height method.
@Test
public void testSetHeight() {
mountainBike.setHeight(40);
assertEquals(40, mountainBike.seatHeight);
}
This tests if the height of the mountain bike can handle user input.
@Test
public void testMountainBikeMethods() {
mountainBike.applyBrake(5);
assertEquals(10, mountainBike.speed);
mountainBike.speedUp(10);
assertEquals(20, mountainBike.speed);
}
This tests if the mountain bike can speed up and brake.
@Test
void testToString() {
String expected = “No of gears are 6\nspeed of bicycle is 25\nseat height is 10”;
assertEquals(expected, mountainBike.toString());
}
}
This is supposed to test that the code has the expected output.
For the final test, I wanted to up the ante. What if I could test the limits of the code?
@Test
public void testSpeedLimits() {
MountainBike mb = new MountainBike(3, 100, 25);
mb.setSpeed(0);
assertEquals(0, mb.getSpeed(), “No negative speed!”);
assertThrows(IllegalArgumentException.class, () -> mb.setSpeed(-10), “No negative speed!”);
}
Overall, this was an interesting challenge. The main difficulty was finding the code to do this project on. There was code that was too easy thus difficult to generate meaningful tests on. There was also code that was too complicated which made it difficult to make a significant number of tests. In the end, it was nice to get some practice.
From the blog My Journey through Comp Sci by Joanna Presume and used with permission of the author. All other rights reserved by the author.