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

CodeIgniter Test Application for ci-phpunit-test
31 stars 20 forks source link

Testing controller method which has no output but returns #23

Closed Tilogorn closed 4 years ago

Tilogorn commented 4 years ago

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?

kenjis commented 4 years ago

@Tilogorn $this->request() returns view (echoed strings).

If you want to do unit testing: https://github.com/kenjis/ci-phpunit-test/blob/master/docs/FunctionAndClassReference.md#unittestcasenewcontrollerclassname

Tilogorn commented 4 years ago

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);
  }
}