Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6880233
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:56:54+00:00 2026-05-27T04:56:54+00:00

I’m a relatively new convert to unit testing in general and I’ve run into

  • 0

I’m a relatively new convert to unit testing in general and I’ve run into a stumbling block here:

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 (MockFtpServer), but nothing readily available for PHP.

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!

Please note that I’ve been working with PHPUnit and require assistance with that framework specifically.


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:

public function connect($conn_name, $opt=array())
{
  if ($this->ping($conn_name)) {
    return TRUE;
  }

  $r = FALSE;

  try {    
    if ($this->conns[$conn_name] = ftp_connect($opt['host'])) {
      ftp_login($this->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;
}

UPDATE/SOLUTION SUMMARY

Problem Summary

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?

Solution Summary

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.

UPDATE 2

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:

Mocking php global functions for unit testing

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T04:56:54+00:00Added an answer on May 27, 2026 at 4:56 am

    Two approaches that come to mind:

    1. Create two adapters for your FTP class:

      1. The “real” one that uses PHP’s ftp functions to connect to the remote server, etc.
      2. A “mock” one that does not actually connect to anything and only returns seeded data.

        The FTP class’ connect() method then looks like this:

        public function connect($name, $opt=array())
        {
          return $this->getAdapter()->connect($name, $opt);
        }
        

        The mock adapter might look something like this:

        class FTPMockAdapter
          implements IFTPAdapter
        {
          protected $_seeded = array();
        
          public function connect($name, $opt=array())
          {
            return $this->_seeded['connect'][serialize(compact('name', 'opt'))];
          }
        
          public function seed($data, $method, $opt)
          {
            $this->_seeded[$method][serialize($opt)] = $data;
          }
        }
        

        In your test, you would then seed the adapter with a result and verify that connect() is getting called appropriately:

        public function setUp(  )
        {
          $this->_adapter = new FTPMockAdapter();
          $this->_fixture->setAdapter($this->_adapter);
        }
        
        /** This test is worthless for testing the FTP class, as it
         *    basically only tests the mock adapter, but hopefully
         *    it at least illustrates the idea at work.
         */
        public function testConnect(  )
        {
          $name    = '...';
          $opt     = array(...);
          $success = true
        
          // Seed the connection response to the adapter.
          $this->_adapter->seed($success, 'connect', compact('name', 'opt'));
        
          // Invoke the fixture's connect() method and make sure it invokes the
          //  adapter properly.
          $this->assertEquals($success, $this->_fixture->connect($name, $opt),
            'Expected connect() to connect to correct server.'
          );
        }
        

      In the above test case, setUp() injects the mock adapter so that tests can invoke the FTP class’ connect() method without actually triggering an FTP connection. The test then seeds the adapter with a result that will only be returned if the adapter’s connect() method were called with the correct parameters.

      The advantage to this method is that you can customize the behavior of the mock object, and it keeps all of the code in one place if you need to use the mock across several test cases.

      The disadvantages to this method are that you have to duplicate a lot of functionality that has already been built (see approach #2), and arguably you’ve now introduced another class that you have to write tests for.

    2. An alternative is to use PHPUnit’s mocking framework to create dynamic mock objects in your test. You’ll still need to inject an adapter, but you can create it on-the-fly:

      public function setUp(  )
      {
        $this->_adapter = $this->getMock('FTPAdapter');
        $this->_fixture->setAdapter($this->_adapter);
      }
      
      public function testConnect(  )
      {
        $name = '...';
        $opt  = array(...);
      
        $this->_adapter
          ->expects($this->once())
          ->method('connect')
          ->with($this->equalTo($name), $this->equalTo($opt))
          ->will($this->returnValue(true));
      
        $this->assertTrue($this->_fixture->connect($name, $opt),
          'Expected connect() to connect to correct server.'
        );
      }
      

      Note that the above test mocks the adapter for the FTP class, not the FTP class itself, as that would be a rather silly thing to do.

      This approach has advantages over the previous approach:

      • You’re not creating any new classes, and PHPUnit’s mocking framework has its own test coverage, so you don’t have to write tests for the mock class.
      • The test acts as documentation for what is happening ‘under the hood’ (although some might contend this is not actually a good thing).

      There are some disadvantages to this approach, however:

      • It’s rather slow (in terms of performance) compared to the previous approach.
      • You have to write a lot of extra code in every test that uses the mock (although you can refactor common operations to mitigate some of this).

      See http://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects for more information.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
That's pretty much it. I'm using Nokogiri to scrape a web page what has
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I want use html5's new tag to play a wav file (currently only supported
I am currently running into a problem where an element is coming back from
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.