Note that there are some explanatory texts on larger screens.

plurals
  1. POMocking/stubbing FTP operations in PHPUnit
    primarykey
    data
    text
    <p>I'm a relatively new convert to unit testing in general and I've run into a stumbling block here:</p> <p>How do I test code that connects to and performs operations on a remote FTP server using PHP's built-in ftp functions? Some googling turned up a quick mocking option for Java (<a href="http://mockftpserver.sourceforge.net/" rel="noreferrer">MockFtpServer</a>), but nothing readily available for PHP.</p> <p>I have a suspicion the answer may be to create a wrapper class for PHP's ftp functions that can subsequently be stubbed/mocked to mimic successful/unsuccessful ftp operations, but I'd really appreciate some input from people who are smarter than me!</p> <p>Please note that I've been working with PHPUnit and require assistance with that framework specifically.</p> <hr> <p>As per the request from @hakre the simplified code I want to test looks like the below. I'm essentially asking the best way to test:</p> <pre><code>public function connect($conn_name, $opt=array()) { if ($this-&gt;ping($conn_name)) { return TRUE; } $r = FALSE; try { if ($this-&gt;conns[$conn_name] = ftp_connect($opt['host'])) { ftp_login($this-&gt;conns[$conn_name], $opt['user'], $opt['pass']); } $r = TRUE; } catch(FtpException $e) { // there was a problem with the ftp operation and the // custom error handler threw an exception } return $r; } </code></pre> <p><strong>UPDATE/SOLUTION SUMMARY</strong></p> <p><em>Problem Summary</em></p> <p>I wasn't sure how to test methods in isolation that required communicating with a remote FTP server. How are you supposed to test being able to connect to an outside resource you have no control over, right?</p> <p><em>Solution Summary</em></p> <p>Create an adapter class for the FTP operations, (methods: connect, ping, etc). This adapter class is then easily stubbed to return specific values when testing other code that uses the adapter to perform FTP operations.</p> <p><strong>UPDATE 2</strong></p> <p>I recently came across a nifty trick using namespaces in your tests that allows you to "mock" PHP's built-in functions. While the adapter was the right way to go in my particular case, this may be helpful to others in similar situations:</p> <p><a href="http://marcelog.github.com/articles/php_mock_global_functions_for_unit_tests_with_phpunit.html" rel="noreferrer">Mocking php global functions for unit testing</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload