简体   繁体   中英

In Junit testing, how to comparing two ArrayList<Double> using assertEquals(), and is there an better alternative?

I'm currently writing a Junit test where I use assertEquals() to compare the value of two ArrayList<Double> .

@Test
public void test(){

        QuadraticFormula one = new QuadraticFormula(3, 4, -4);
        List<Double> results = new ArrayList<>();
        results.add(0.66666);
        results.add(-2.0);

        assertEquals(results, one.getRoots());
    }

However, Junit prints out the following failure message:

expected:<[0.66666, -2.0]> but was:<[0.6666666666666666, -2.0]>
junit.framework.AssertionFailedError

Is there anyway I can specify how many decimal places I want the test to compare? I know how to test equality of two double values to certain accuracy, but is there anyway that this can be achieved when comparing two ArrayList of doubles?

I guess you can use BigDecimal instead of Double.

check this SO for more details

You can use NumberFormat or BigDecimal

Below will round-of

    double d = 0.66666666;
    NumberFormat format = new DecimalFormat("#.##");
    System.out.println(format.format(d)); // 0.67
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(bigDecimal); // 0.67

If you don't want to round-of

    double d = 0.66666666;
    DecimalFormat format = new DecimalFormat("#.##");
    format.setRoundingMode(RoundingMode.DOWN);
    System.out.println(format.format(d)); // 0.66
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(2, RoundingMode.DOWN);
    System.out.println(bigDecimal); //0.66

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM