Fix the unit test issue and replace `while (true)` loop with clearer logic in `do … while` loop.