kenjis/ci-app-for-ci-phpunit-test

Testing controller method which has no output but returns

Closed this issue · 2 comments

Assuming I have a controller like this:

<?php

class Welcome extends CI_Controller {
  public function index()
  {
    $solution = $this->getSolution();
    echo 'The solution is ' . $solution;
  }

  public function getSolution()
  {
    return 42;
  }
}

If I would like to test getSolution() in a classical unit testing behaviour, I would call the method directly:

<?php

class Welcome_test extends TestCase
{
  public function test_getSolution()
  {
    $testSolution = $this->request('GET', ['welcome', 'getSolution']);
    $this->assertEquals(42, $testSolution);
    // Failed asserting that null matches expected 200.
  }
}

Unfortunately (understandably), $testSolution is always null as it seems to contain only output. Proof: If I echo "something"; in getSolution(), $testSolution equals "something".

So is there a way to test controller methods directly that are no route methods but simple helper methods that return something?

Or do I have to change my design to define such methods in libraries/helpers?

Thanks a lot @kenjis! That document is a huge addition of your framework I didn't even know about.

Updated test file:

<?php

class Welcome_test extends UnitTestCase
{
  public function test_getSolution()
  {
    $controller = $this->newController('Welcome');
    $actual = $controller->getSolution();
    $this->assertEquals(42, $actual);
  }
}