JUnit test failing using assertEquals on a method that returns a StringBuilder

33 Views Asked by At

In testing a Fleet Management application, multiple tests are failing in regards to making sure that a specific report of vehicles, which returns a StringBuilder, contains the actual data given to it. There are multiple reports and so multiple tests, but they're all failing. Part of the assignment was to replace each instance of string concatenation in the class being tested with a StringBuilder, but the tests were failing before I did that anyway.

The report being returned by the method I'm testing contains the details of each element in a list, and the way I've written the test is asserting the equality of the text data itself, which feels wrong, but I don't know what the better alternative is.

The method being tested in the FleetManagement class:

public StringBuilder allVehiclesReport() 
{
        StringBuilder str = new StringBuilder();
        for (Vehicle vehicle : vehicles) {
            str.append(vehicles.toString());
        }
        return str;
}

And the test method failing:

//setUp() omitted 

@Test
    public void testAllVehiclesReport()
    {
        //load test data, add to appropriate lists
        //run method, assert that string returned contains test data
        fleetMan1.addVehicle(vehicle1);
        fleetMan1.addVehicle(vehicle2);
        assertEquals("Vehicle: Buick Regal Sedan. VIN: 111\nVehicle: Chevy Corvette SportsCar. VIN: 122\n", fleetMan1.allVehiclesReport()); 
    }

I would guess that manually typing out the whole thing might not be the best idea, even though I followed it to the letter, but I don't know what else to do. Part of the failure occurring the first time, when the method returned a String, was that the data being entered would end up out of order, so it would be checking Ford & Chevy against Chevy & Ford, but afaik I can't use contains(), can I? When learning about testing before, we mostly just covered assertEquals.

1

There are 1 best solutions below

0
catch23 On

You have some typo in your code you should add vehicle to string builder instead of vehicles:

public StringBuilder allVehiclesReport() {
        StringBuilder builder = new StringBuilder();
        for (Vehicle vehicle : vehicles) {
            builder.append(vehicle.toString());
        }
        return builder;
}

To verify correctness you could check assert like:

assertEquals(new StringBuilder("expected cars details"), fleetMan1.allVehiclesReport());

Or check that the needed car is presented in response:

var actualResponse = fleetMan.allVehiclesReport().toString();
assertTrue(actualResponse.contains("expected car one"));
assertTrue(actualResponse.contains("expected car two"));

Also, you could use AssertJ assertions:

assertThat(actualResponse.contains("expected car one", "expected car two"))