10

I am very new to PHPUnit and unit-testing, so I have a questing: Can I test a function outside a class like:

    function odd_or_even( $num ) {
    return $num%2; // Returns 0 for odd and 1 for even
}

class test extends PHPUnit_Framework_TestCase {
    public function odd_or_even_to_true() {
        $this->assetTrue( odd_or_even( 4 ) == true );
    }
}

Right now it just returns:

No tests found in class "test".

2 Answers 2

19

You need to prefix your function names with 'test' in order for them to be recognized as a test.

From the documentation:

  1. The tests are public methods that are named test*.

Alternatively, you can use the @test annotation in a method's docblock to mark it as a test method.

There should be no problem calling odd_or_even().

For example:

class test extends PHPUnit_Framework_TestCase {
    public function test_odd_or_even_to_true() {
        $this->assertTrue( odd_or_even( 4 ) == true );
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Theadamlt: also in odd_or_even( 4 ) == true the part == true is redundant, as long as you use assertTrue
+1 for mentioning using the @test annotation. Excellent.
What's the best way to import functions to a test? I tried require('function.php'), but that cause a 1) test::test_me Exception: Serialization of 'Closure' is not allowed
0

In recent versions of phpunit, this is how I write test.php to test a single function:

<?php
use PHPUnit\Framework\TestCase;

class test extends TestCase
{
   public function test_odd_or_even_to_true()
   {
      $this->assertTrue(
         odd_or_even(4) == 0
      );
   }
}

And I run the test this way:

./phpunit --bootstrap file_with_source_code.php ./tests/test.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.