Issue
I have a Car
class with a category field which is String
:
public class Car {
private String category;
public Car(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
And I have this method which is filtering out elements from array based on String
using the contains()
method to keep only sport cars. I know this is bad idea, just trying to write my very first unit test. Can you please help me to understand where to start. In general what are the best practices for testing loop filtering logic.
private List<Car> filterOutEverythingExceptSportCars(List<Car> cars) {
List<Car> filteredCarsList = new ArrayList<>();
for (int i = 0; i < cars.size(); i++) {
if (cars.get(i).getCategory().contains("sport")) {
filteredCarsList.add(cars.get(i));
}
}
return filteredCarsList;
}
Solution
First of all you need to make your method testable. In your implementation it's a private instance method. Since you're not using anything else from the instance, you could make it a package-private static method:
static List<Car> filterOutEverythingExceptSportCars(List<Car> cars) {
List<Car> filteredCarsList = new ArrayList<>();
for (Car car: cars) {
if (!car.getCategory().contains("sport")) {
filteredCarsList.add(car);
}
}
return filteredCarsList;
}
Now you can easily write a unit test with input and output lists to be compared:
@Test
public static void testFilterOutEverythingExceptSportCars() {
List<Car> cars = ...;
List<Car> actual = filterOutEverythingExceptSportCars(cars);
List<Car> expected = ...;
assertEquals(expected, actual);
}
You only need to statically import the filterOutEverythingExceptSportCars
method and have the test class in the same package as the implementation.
Please note that the improvement of the for-loop is up to you to apply and not mandatory. I Also didn't change the naming or if-condition to match. Just write your tests and iterate over your implementation until you like it best...
Answered By - tynn