How do you test code that uses immutability?

Testing code that uses immutability can be effective by employing various strategies such as using unit tests, leveraging mocking frameworks, and utilizing property-based testing. Immutability helps in simplifying the testing process as immutable objects do not change state, leading to fewer side effects and more predictable behavior.


    class ImmutablePoint {
        private $x;
        private $y;

        public function __construct($x, $y) {
            $this->x = $x;
            $this->y = $y;
        }

        public function getX() {
            return $this->x;
        }

        public function getY() {
            return $this->y;
        }
        
        public function move($dx, $dy) {
            return new ImmutablePoint($this->x + $dx, $this->y + $dy);
        }
    }

    // Unit test
    $originalPoint = new ImmutablePoint(1, 2);
    $newPoint = $originalPoint->move(3, 4);

    // Assert original was not modified
    assert($originalPoint->getX() === 1);
    assert($originalPoint->getY() === 2);
    
    // Assert new point is correct
    assert($newPoint->getX() === 4);
    assert($newPoint->getY() === 6);
    

immutability unit testing PHP testing immutable objects