How to unit test a data extraction method

543 Views Asked by At

I have created a method which interacts with a framework, pulling out order items which have a completed status.

However, how can I unit test my method to ensure it behaves correctly...

class A
{
    public function extractData()
    {
        // extract data from framework
        $dataCollection = FrameworkX->getDataCollection('sales/orders');
        $dataCollection->filter('state', 'complete');

        return $extractedData;
    }
}


ClassATest
{
    public function test_extracted_data_contains_only_items_with_complete_status {
        $sut  = new ClassA();
        $sut->extractData();

        // What is the assertion here?
    }

}
1

There are 1 best solutions below

4
On BEST ANSWER

You can iterate through the collection and assert that every item is in 'Complete' state.

However what you're doing here is called an integration test.

You're not testing your method (unit), but you test how the framework behave (get's the data from the storage) and how the filter method works.

If you want to have a Unit-Test have a look at this article. You should create a Stub for your FramewokX->getDataCollection() method.

How to test methods with third party dependencies

If the FrameworkX is final then you can declare an interface:

interface iDataSource
{
    public function getDataCollection($path);
}

and a new class:

class DataSource implements iDataSource
   {
      public function getDataCollection($path)
      {
         //no need to test this method, it's just a wrapper
         return  FrameworkX->getDataCollection('sales/orders');
      }
    }

In your class A create a constructor:

public function __construct(iDataSource $dataSource)
 {
   $this->dataSource= $dataSource;
 }

And change the extractData method to use it.

public function extractData()
{
    // extract data from framework
    $dataCollection = $dataSource->getDataCollection('sales/orders');
    $dataCollection->filter('state', 'complete');

    return $extractedData;
}

Let's assume that you're using PHPUnit.

 public function test_extracted_data_contains_only_items_with_complete_status ()
 {
    // Create a stub for the DataSource class.
    $stub = $this->getMockBuilder('DataSource')
                 ->getMock();

    // Configure the stub.
    $stub->method('getDataCollection')
         ->willReturn(preconfigured_collection_with_all_statuses_here);

    $sut  = new ClassA($stub); //create a new constructor and pass the stub
    $sut->extractData();
    // and after that verify that your method filtered out non complete statuses
 }