Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have private functions in a phpunit class?

Tags:

php

phpunit

I have some public functions in "DefaultControllerTest".

But these public functions have some common code in them - for example, I test a few different pages to make sure a bit of text is appearing. So the code is similar.

So I put the common code into a private function, which I can then call from each public function - from each test.

But I am getting this error:

Test method "testHeader" in test class "MyApp\MyBundle\Tests\Controller\DefaultControllerTest" is not public.

testHeader is the private function that I test from each public function.

So how can I have a private function in this class?

like image 262
b85411 Avatar asked Dec 15 '14 07:12

b85411


2 Answers

Functions starting with 'test' are automatically called from PHPUnit and so need to be public.

If you edit the name of the function so that it no longer starts with 'test', it won't be called directly from PHPUnit and the error message will disappear.

like image 164
Haim Evgi Avatar answered Oct 13 '22 20:10

Haim Evgi


To explain a little more thoroughly, there are two ways a function inside a test class can be deemed to be a test method (as opposed to a supporting private function/method called by the test code). They are:

1) Have @test as an annotation in the method's doc block;

or

2) Name the method starting with 'test'

And these test methods should be public.

The minimalist doc block would be:

/**
* @test
*/

to mark any method as a test, what ever it is named.

like image 36
NULL pointer Avatar answered Oct 13 '22 20:10

NULL pointer