I am creating a class with some unit tests, but i am not able to pass few tests. Example is shown below.
class OffsetTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider getIllegalOffsets
* @expectedException \InvalidArgumentException
* @param $offset
*/
public function testIllegalParameters($offset)
{
new \OffsetEncodingAlgorithm($offset);
$this->fail('Exception should be thrown');
}
/**
* Data provider for {@link OffsetTest::testIllegalParameters()}
* @return array
*/
public function getIllegalOffsets()
{
return [
[-1],
];
}
}
<?php
class Offset
{
public function __construct(int $offset = 13)
{
try {
if ($offset < 0) {
throw new Exception('Exception should be thrown');
}
} catch (Exception $e) {
return $e->getMessage();
}
$this->offset = $offset;
}
}
I want all to be passed
While testing for the testIllegalParameters()
which expects an exception in return, you don't have to use try-catch
block. Just throw an exception in an if
condition simply.
Secondly throw a correct type of exception that is defined in the test case InvalidArgumentException
class Offset
{
public function __construct(int $offset = 13)
{
if ($offset < 0) {
throw new InvalidArgumentException('Offset should be greater than equal to zero');
} else {
$this->offset = $offset;
}
}
}