PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How can I mock outputting messages to the error log with PHPUnit?

 May 16, 2022     automated-tests, error-logging, mocking, php, phpunit     No comments   

Issue

In this answer it mentions using expectOutputString() to, well, expect output strings in PHPUnit.

I also need to do sort of the counterpart of this, which is to tell a mock to output a string.

I was previously using $mock->will($this->throwException(Exception('foo')) to have my mock throw an exception but now instead of throwing an exception I need it to log the error and NOT re-throw the exception, which means I need my mock to output a string just as error_log() does in the method I'm trying to mock, so that my test can expect the string.

Does this make sense? Is it possible to do? Does PHPUnit offer a way to do it?


Solution

From the testability point of view, it's always better to abstract the error logging into a class. If you make direct calls to error_log() you will have difficulties checking the calls made.

If you can't refactor your code and use a class for logging errors, you could try setting a custom error handler that will store the messages in some place, and then check those messages at the test, after the relevant call.

But if you can, it's better to create a class with methods that abstract native php error logging. This class will be a dependency of the class under test. You can either pass it as a constructor mandatory argument, or have the class create it automatically, but allow to set it externally. Obviously, in the test you would inject a mock of that "ErrorLogger" class with expectations



Answered By - gontrollez
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing