Post

Check Money Exactly With BigDecimal in REST Assured

Learn how REST Assured reads JSON numbers, why the default Float can't hold money, how to read decimals as BigDecimal with JsonConfig, why comparesEqualTo beats equalTo, and when closeTo is the right choice.

Check Money Exactly With BigDecimal in REST Assured

A bank statement has to add up: the opening balance plus every transaction is exactly the closing balance, not almost. Your statement test adds the six amounts, and the sum comes back as 1407.650001525879. Then a check of the opening balance fails, because 1000.00 isn’t 1000. In this guide, you’ll learn how REST Assured reads JSON numbers, read money as BigDecimal, and compare amounts exactly.

Level: Intermediate · Time: 20 minutes · Part of: Module 3: Validating Responses in Depth, section 3

What You’ll Build

You’ll build a test class called NumbersAndMoneyTest with seven tests. They read the same transactions with three number types, and prove which comparisons are exact, which are strict about scale, and which allow a tolerance.

All seven tests send this request and check this response:

1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1001/transactions HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"balance":{"opening":1000.00,"closing":2407.65},"transactions":[{"id":"tx-1","amount":2500.00, ...}, ...]}

When you’re done, Maven reports seven passing tests:

1
2
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • See the default number types.
  • Read money as BigDecimal.
  • Add up amounts exactly.
  • Compare approximate values.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create NumbersAndMoneyTest in a new section_03 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (NumbersAndMoneyTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Filter JSON Lists With GPath in REST Assured.

Out of scope: this guide doesn’t cover setting the number type once for a whole suite, or extracting amounts into Java objects; they’re taught in Module 5 and Module 4.

Understand JSON Numbers in REST Assured

The problem. JSON has one number type, but Java has many. REST Assured has to pick one for each number in the body, and the default it picks for decimals can’t hold most amounts exactly. For one value you rarely notice. When a test adds amounts together, the small errors add up, and an exact statement check fails.

The concept. REST Assured picks a Java type for each number:

  • A whole number becomes an Integer, or a Long when it’s too big for an Integer.
  • A decimal becomes a Float by default, or a Double when it’s too big for a Float.

A Float holds about seven significant digits in binary, so -42.35 is stored as the nearest binary value, not as -42.35. JsonConfig changes the type used for decimals: NumberReturnType.BIG_DECIMAL reads them as BigDecimal, which stores decimal values exactly. A BigDecimal has a value and a scale, the number of digits after the point, so 1000.00 has scale 2 and 1000 scale 0.

When to use each. Pick the number type and the matcher from what the value means:

ValueNumber typeMatcher
A count, an id or a statusDefault (Integer)equalTo(6)
MoneyBIG_DECIMALcomparesEqualTo(new BigDecimal("2407.65"))
A measurementDOUBLEcloseTo(-42.35, 0.001)
A quick check of a decimalDefault (Float)equalTo(-42.35f)

Read money as BigDecimal, and compare its value, not its scale.

Meet the API Under Test

The tests use the Transactions API and account acc-1001 from Filter JSON Lists With GPath in REST Assured. The parts that matter here are the balance and the amounts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{
    "balance": { "opening": 1000.00, "closing": 2407.65 },
    "transactions": [
        { "id": "tx-1", "type": "CREDIT", "amount": 2500.00, ... },
        { "id": "tx-2", "type": "DEBIT", "amount": -42.35, ... },
        { "id": "tx-3", "type": "DEBIT", "amount": -1100.00, ... },
        { "id": "tx-4", "type": "DEBIT", "amount": -60.00, ... },
        { "id": "tx-5", "type": "DEBIT", "amount": -40.00, ... },
        { "id": "tx-6", "type": "CREDIT", "amount": 150.00, ... }
    ]
}

The statement adds up:

MovementSum
The four debits-1242.35
The two credits2650.00
All six amounts1407.65

And 1000.00 + 1407.65 is the closing balance, 2407.65.

Your tests check these fields:

  • transactions[1].amount, -42.35, the first amount that isn’t a whole number.
  • balance.opening and balance.closing, which carry two decimals.
  • The sums of transactions.amount, which only come out exact with BigDecimal.

See the Default Number Types

Set Up the Test Class

Goal: create the test class with a helper that sends the request, and one that reads decimals as BigDecimal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.javanibble.module_03.section_03;

import static io.restassured.RestAssured.given;
import static io.restassured.config.JsonConfig.jsonConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.comparesEqualTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.not;

import com.javanibble.transactions.TransactionsApi;

import io.restassured.common.config.NumberReturnType;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;

import java.math.BigDecimal;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class NumbersAndMoneyTest {

    private static TransactionsApi api;

    @BeforeAll
    static void startApi() {
        api = TransactionsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification transactionsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH);
    }

    private static ValidatableResponse transactions(RequestSpecification request) {
        return request.when().get("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID).then();
    }

    private static RequestSpecification withBigDecimals() {
        return transactionsApi().config(config().jsonConfig(jsonConfig().numberReturnType(NumberReturnType.BIG_DECIMAL)));
    }
}

What’s happening:

  • transactions(request) sends the transactions request with whatever specification it’s given, so each test can choose the number type.
  • withBigDecimals() sets JsonConfig on the request, so every decimal in its response is read as a BigDecimal.
  • config(..) applies the setting to this request only, as HeaderConfig did in Send Headers and Cookies in REST Assured.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Since REST Assured 6.3, NumberReturnType lives in io.restassured.common.config. The older JsonPathConfig.NumberReturnType is deprecated, so import the new one.

Read a Whole Number

Goal: show that a whole number is an Integer.

1
2
3
4
@Test
void wholeNumbersAreIntegers() {
    transactions(transactionsApi()).body("transactions.size()", equalTo(6));
}

What’s happening:

  • size() returns a whole number, which REST Assured gives you as an Integer.
  • equalTo(6) compares with an Integer, so it matches. No number type needs to change for counts.

Checkpoint: run NumbersAndMoneyTest from your IDE. One test runs and passes.

Read a Decimal as a Float

Goal: show what the default Float matches and what it doesn’t.

1
2
3
4
5
6
7
@Test
void decimalsAreFloatsByDefault() {
    transactions(transactionsApi())
        .body("transactions[1].amount", instanceOf(Float.class))
        .body("transactions[1].amount", equalTo(-42.35f))
        .body("transactions[1].amount", not(equalTo(-42.35)));
}

What’s happening:

  • instanceOf(Float.class) proves the default type.
  • equalTo(-42.35f) passes, because both sides are the same Float.
  • equalTo(-42.35) fails, because -42.35 is a Double, and Float.equals(..) is false for any Double. The test wraps it in not(..) to prove it.

Checkpoint: run the class again. Two tests pass.

A Double never equals a Float. Without not(..), the check fails with Expected: <-42.35> and Actual: <-42.35F>: the values look the same, and the F is the only clue.

Read Money as BigDecimal

Read Decimals as BigDecimal

Goal: read an amount and the closing balance as exact decimals.

1
2
3
4
5
6
7
@Test
void decimalsAsBigDecimal() {
    transactions(withBigDecimals())
        .body("transactions[1].amount", instanceOf(BigDecimal.class))
        .body("transactions[1].amount", equalTo(new BigDecimal("-42.35")))
        .body("balance.closing", equalTo(new BigDecimal("2407.65")));
}

What’s happening:

  • withBigDecimals() makes transactions[1].amount a BigDecimal.
  • The expected values are built from strings, so they’re exact too.
  • equalTo(..) passes here because both sides have the same value and the same scale, two decimals.

Checkpoint: run the class again. Three tests pass.

Always build the expected value from a string. new BigDecimal(-42.35) takes a double, which is already inexact: it’s -42.35000000000000142108547152020037174224853515625.

Compare the Value, Not the Scale

Goal: show why equalTo(..) fails on 1000.00 and comparesEqualTo(..) doesn’t.

1
2
3
4
5
6
@Test
void equalToIsStrictAboutScaleButComparesEqualToIsNot() {
    transactions(withBigDecimals())
        .body("balance.opening", not(equalTo(new BigDecimal("1000"))))
        .body("balance.opening", comparesEqualTo(new BigDecimal("1000")));
}

What’s happening:

  • BigDecimal.equals(..) compares the value and the scale, so 1000.00 (scale 2) isn’t equal to 1000 (scale 0).
  • Without the not(..), the check fails with Expected: <1000> and Actual: <1000.00>.
  • comparesEqualTo(..) uses compareTo(..), which compares only the value. For money, that’s almost always what you want, so use it by default.

Checkpoint: run the class again. Four tests pass.

Add Up Amounts Exactly

Sum a Filtered List

Goal: add up the debits and the credits.

GPath’s sum() adds a list of numbers. With BigDecimal values, the result is exact:

1
2
3
4
5
6
@Test
void sumsAreExactWithBigDecimal() {
    transactions(withBigDecimals())
        .body("transactions.findAll { it.type == 'DEBIT' }.amount.sum()", comparesEqualTo(new BigDecimal("-1242.35")))
        .body("transactions.findAll { it.type == 'CREDIT' }.amount.sum()", comparesEqualTo(new BigDecimal("2650")));
}

What’s happening:

  • findAll { .. }.amount collects the amounts of one type, and sum() adds them.
  • 2650 has no decimals, but the sum is 2650.00. comparesEqualTo(..) doesn’t mind the different scale.

Checkpoint: run the class again. Five tests pass.

Check the Net Movement

Goal: add up all six amounts exactly.

1
2
3
4
5
@Test
void theNetMovementIsExact() {
    transactions(withBigDecimals())
        .body("transactions.amount.sum()", comparesEqualTo(new BigDecimal("1407.65")));
}

What’s happening:

  • 2500.00 - 42.35 - 1100.00 - 60.00 - 40.00 + 150.00 is exactly 1407.65.
  • With BigDecimal values, the sum is exact. With the default Float values, it isn’t, as you’ll see in Make a Test Fail.

Checkpoint: run the class again. Six tests pass.

A path reads from one place in the body, so it can’t add values from two top-level fields. "balance.opening + transactions.amount.sum()" throws The parameter "transactions" was used but not defined. Check each value with its own path.

Compare Approximate Values

Allow a Tolerance With closeTo

Goal: check a value that’s approximate on purpose.

Not every number is money. For a measurement, such as a duration or an exchange rate from a model, a small difference is fine, and closeTo(..) allows a tolerance:

1
2
3
4
5
@Test
void closeToForValuesThatAreApproximateOnPurpose() {
    transactions(transactionsApi().config(config().jsonConfig(jsonConfig().numberReturnType(NumberReturnType.DOUBLE))))
        .body("transactions[1].amount", closeTo(-42.35, 0.001));
}

What’s happening:

  • NumberReturnType.DOUBLE reads decimals as Double.
  • closeTo(-42.35, 0.001) passes when the value is within 0.001 of -42.35.

Checkpoint: run the class again. All seven tests pass.

closeTo(..) matches only Double values. On the default Float it fails even though the value is within the tolerance: Expected: a numeric value within <0.001> of <-42.35>, Actual: <-42.35F>. Set NumberReturnType.DOUBLE first.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-03 -Dtest=NumbersAndMoneyTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_03.section_03.NumbersAndMoneyTest
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.463 s -- in com.javanibble.module_03.section_03.NumbersAndMoneyTest
[INFO]
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In theNetMovementIsExact, replace withBigDecimals() with transactionsApi() and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   NumbersAndMoneyTest.theNetMovementIsExact:98 1 expectation failed.
JSON path transactions.amount.sum() doesn't match.
Expected: a value equal to <1407.65>
  Actual: <1407.650001525879>

Each Float amount was slightly off, and adding six of them made the error visible. This is the statement from the opening, and the reason money needs BigDecimal.

Change transactionsApi() back to withBigDecimals() and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
Expected: <-42.35> but Actual: <-42.35F>A Double was compared with the default FloatUse -42.35f, or read BigDecimal
Expected: <1000> but Actual: <1000.00>equalTo(..) on a BigDecimal compares the scaleUse comparesEqualTo(..)
Actual: <1407.650001525879> for a sumThe amounts were added as Float valuesRead them with NumberReturnType.BIG_DECIMAL
Expected: a numeric value within ... but Actual: <-42.35F>closeTo(..) was used on a FloatSet NumberReturnType.DOUBLE

Try It Yourself

Exercise 1: Check the Groceries and the Rent

Add a test called groceriesAndRentAreExact that reads BigDecimal values and checks that the grocery amounts add up to -102.35, and that the rent amount is -1100.

Hint

Combine sumsAreExactWithBigDecimal with find { .. } from the previous sections. The rent is -1100.00, so compare it with comparesEqualTo(..).

Solution
1
2
3
4
5
6
@Test
void groceriesAndRentAreExact() {
    transactions(withBigDecimals())
        .body("transactions.findAll { it.category == 'GROCERIES' }.amount.sum()", comparesEqualTo(new BigDecimal("-102.35")))
        .body("transactions.find { it.category == 'RENT' }.amount", comparesEqualTo(new BigDecimal("-1100")));
}

Exercise 2: Check the Whole Statement

Add a test called theStatementAddsUp that reads BigDecimal values and checks, in one chain: the opening balance is 1000 and the closing balance is 2407.65, through a root path on balance; the net movement is 1407.65; the largest amount is 2500; and the positive amounts add up to 2650.

Hint

Use rootPath("balance") and noRootPath(), as in Shorten JSON Paths With Root Paths in REST Assured. GPath has max() as well as sum(), and whole numbers are safe inside a closure.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void theStatementAddsUp() {
    transactions(withBigDecimals())
        .rootPath("balance")
        .body("opening", comparesEqualTo(new BigDecimal("1000")))
        .body("closing", comparesEqualTo(new BigDecimal("2407.65")))
        .noRootPath()
        .body("transactions.amount.sum()", comparesEqualTo(new BigDecimal("1407.65")))
        .body("transactions.amount.max()", comparesEqualTo(new BigDecimal("2500")))
        .body("transactions.findAll { it.amount > 0 }.amount.sum()", comparesEqualTo(new BigDecimal("2650")));
}

Summary

You built NumbersAndMoneyTest, which reads the same transactions as Integer, Float, BigDecimal and Double values, and checks counts, amounts, balances and sums with the matcher each one needs. The statement now adds up to exactly 1407.65.

  • REST Assured reads whole numbers as Integer and decimals as Float by default.
  • A Float is fine for a quick check with the f suffix, but it can’t hold money exactly, and its errors add up in a sum.
  • Set NumberReturnType.BIG_DECIMAL with JsonConfig to read decimals exactly, and build expected values from strings.
  • Compare money with comparesEqualTo(..), which ignores the scale; equalTo(..) fails on 1000.00 against 1000.
  • Keep closeTo(..), with NumberReturnType.DOUBLE, for values that are approximate on purpose.

Here are the commands you used in this guide:

1
mvn test -pl module-03 -Dtest=NumbersAndMoneyTest

What’s Next

Next: continue with Pick the Right Hamcrest Matcher in REST Assured, which picks the right matcher for each check, from hasItems and containsInAnyOrder to allOf and anyOf.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.