How to UnitTest a ShellTask


I wrote an Shell Task performing the creation of some XML Document.
Now I’d like to Unit Test this Task.
My Question is how. And my Problem is, that the MockBuilder is not really creating a Mock.

Here’s the Code of my setUp() Function.

public function setUp()
        $this->io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock();

        $this->PrepareCatalog = $this->getMockBuilder('Mercateo\Shell\Task\PrepareCatalogTask')

The “PrepareCatalogTask” is (of Course) invoked by a Shell.

I’ve written a simple math Function in the PrepareCatalogTask:

public function mathAdd($a,$b)
        $c = $a + $b;
        return $c;

Here is the Error Message i’m getting:

2) Mercateo\Test\TestCase\Shell\Task\PrepareCatalogTaskTest::testMathAdd
Failed asserting that null matches expected 9.

So, the PrepareCatalogTask Object has not been instantiated respectively the Mock Builder is not doing what I hope he’s doing.

Any suggestions?

Because you’re not calling setMethods() on the MockBuilder for your shell task, all of the classes methods are mocked. Instead either don’t use a mock, or only mock _stop with

    $this->PrepareCatalog = $this->getMockBuilder('Mercateo\Shell\Task\PrepareCatalogTask')

How to do unit test of datatrait? Or how we can use datatrait method in unit test file CAKEPHP3

Not sure what DataTrait. In general you can use PHPUnit to generate classes for a trait and then test the trait methods with that object. If your trait requires methods to be implemented by the class that uses the trait I would create a simple class that uses your trait and then test that.

In the Traits folder, we are creating trait files, So I want to use One of the Trait methods in my UNIT test file, but I was not able to use it.

$obj = $this->getObjectForTrait(DataTrait::class);
$mock = $this->getMockForTrait('/src/Controller/Traits/DataTrait.php');

I have tried like above but it’s loading Test trait, not the actual trait that I want to use.

What do you mean that a ‘test trait’ is being loaded? I’ve not seen that behavior before in PHPUnit.