1

I know how to set an expected exception while unit testing using PHPUnit's setExpectedException() method and/or its equivalent annotation.

But for some reason I'm not able to do the same while testing some logic around a fopen() here is an example:

class AbstractFileReaderTest extends \PHPUnit_Framework_TestCase
{
    public function test_invalidFileException()
    {
        $filePath = 'incorrect/file/path.csv';

        $this->setExpectedException(\Exception::class);

        fopen($filePath, "r");
    }
}
3
  • 1
    fopen() doesn't throw an exception, it generates a warning (and returns a Boolean false).... unless you've overridden the PHP error handler to throw an exception instead of that normal behaviour Commented Jun 29, 2015 at 15:35
  • 1
    besides @MarkBaker's comment - setExpectedException's first argument should be a string. Commented Jun 29, 2015 at 15:38
  • Thanks both :), Chris \Exception::class is string ;) Commented Jun 29, 2015 at 15:53

1 Answer 1

2

For unit test on file system it's better to use something like vfsStream

vfsStream is a stream wrapper for a virtual file system and for tests it's cleaner solution to write there then real file system.

Sign up to request clarification or add additional context in comments.

1 Comment

Very interesting and useful tool, thanks. But is that alright to have posix installed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.