How to write Unit Test in cakephp 4.x.x

Hello, Can someone please give me an example, how am I supposed to write a unit test for a Controller’s method? I am familiar with the examples in the documentation, but that does not help me.
I need an example for a specific controller’s method. What are the steps? Thanks in advance.

The documentation on Controller Integration Testing is pretty thorough on this topic. What does your test look like so far, and what’s not working about it?

1 Like

Hello, Thanks for your response. I know how to do integration tests, but this is not the point. I want to do Unit Tests. Let me give you an example of what I am trying to do and the test fails.
I have this link: $this->get(“localhost/myProject/Controller/action”);
In the response body this generates:

Signing document

When I try to assert: $this->assertResponseContains(‘Signing document’); It fails.
What am I doing wrong?

Is “localhost/myProject/Controller/action” the actual URL you’re trying to get? Because that looks very wrong. You should be doing $this->assertResponseOk(); first, to make sure the request succeeded. Then (string)$this->_response->getBody() will get you the actual body contents for debugging purposes.

I feel your pain.

The advice from @Zuluru should get you on the road. But when the initial $this->assertResponseOk() fails, I have found to pretty inconvenient to discover what DID happen.

Lately I have been using a DebugTrait in my tests that includes this knocked-together bit:

    public function writeFile($name = 'debug')
    {
        $file_name = "$name.html";
        $file = new File(WWW_ROOT . $file_name);
        $result = $file->write($this->_getBodyAsString(), 'w', true);
        debug($result ? "http://dev.ampfg4.com/$file_name" : "failed to write $file_name");
        $file->close();
    }

Then when I have a test that is giving me trouble I can use the trait method like this:

        $this->get("orders/delete/$order->id/$hash");
        $this->writeFile();

Then in the test results pane (I use PHPStorm for dev and testing) I see this:

In my IDE, this is a live link and I can see the page that the test generated.

If there was a 500 error or some other anomalous result, I can see what was returned.

Notes:

  • The page is just dumped into webroot.
  • The File class is deprecated but works fine.
  • Make $name dynamic if you are using a dataProvider for your test and need to see multiple resulting pages.