Creare unit test in PHP senza librerie

Mattepuffo's logo
Creare unit test in PHP senza librerie

Creare unit test in PHP senza librerie

PHP ha delle ottime librerie per creare unit test.

Ma su un progetto molto piccolo potrebbero non essere necessarie.

In questo articolo vediamo un paio di esempi di unit test senza usare librerie.

Partiamo dal primo esempio:

assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_EXCEPTION, 1);

function somma($a, $b) {
  return $a + $b;
}

try {
  assert(somma(2, 3) === 5);
  assert(somma(-1, 1) === 0);
  assert(somma(0, 0) === 0);
  echo "Tutti i test sono passati\n";
} catch (AssertionError $e) {
  echo "Test fallito: " . $e->getMessage() . "\n";
}

Volendo fare un esempio un pò più avanzato:

function test($name, $callback): void {
  try {
    $callback();
    echo "$name\n";
  } catch (AssertionError $e) {
    echo "$name - " . $e->getMessage() . "\n";
  }
}

function somma($a, $b) {
  return $a + $b;
}

test('Somma di due numeri positivi', function () {
  assert(somma(2, 3) === 5);
});

test('Somma con zero', function () {
  assert(somma(0, 0) === 0);
});

Enjoy!


Condividi

Commentami!