Phpunit tests gives warning no tests found in class - php

I am trying to learn how to test with phpunit and laravel. When start the test using phpunit command, I am getting a warning :
There was 1 failure:
1) Warning
No tests found in class "PostsTest".
FAILURES!
Tests: 2, Assertions: 1, Failures:
My test classname and filename matches. I have read other problems about unmatching names. my filename is PostsTest.php and my test file :
class PostsTest extends ApiTester {
public function it_fetches_posts()
{
$this->times(5)->makePost();
$this->getJson('api/v1/posts');
$this->assertResponseOk();
}
private function makePost($postFields=[])
{
$post = array_merge([
'title' => $this->fake->sentence,
'content' => $this->fake->paragragraph
], $postFields);
while($this->times --)Post::create($post);
}
}
if necessary my ApiTester :
use Faker\Factory as Faker;
class ApiTester extends TestCase {
protected $fake;
protected $times = 1;
function __construct($faker)
{
$this->fake = Faker::create();
}
}
I dont have any clue where the error is. Laravel or my local phpunit settings or anything else. Any helps is appreciated.
Thanks.

Annotations are the answer.
/** #test */
public function it_tests_something()
{
...
}
Adding that #test tells phpunit to treat the function as a test, regardless of the name.

The only methods that PHPUnit will recognize as tests are those with names starting with test.
So you should rename the it_fetches_posts() method to test_it_fetches_posts or testItFetchesPosts. The camel case naming is optional but useful if you use the --testdox option later.
Also, as stated in other answer you can also add the #test annotation to any method and it will be considered a test by PHPUnit.

Either begin its name with word 'test' like test_something_should_work or update the test docs with this annotation /** #test */

Additionally, consider a case where you are testing a class A that requires a class B (that you will mock). When $a->someMethod($mocked_B_class) is called, make sure you don't have any warnings in it such as trying to access a property of an array like you would access the property of a class ($array = ['one','two']; $array->one).
In this case it wont give you any information about the test or the error

Related

Unit-Test code coverage not determined correctly

When using the #covers-annotation, it's not been taken into account when displaying the code coverage.
No matter if I just "cover" the class, or the method, or both.
Test:
/**
* #covers \App\Controller\UserEditController
*/
class UserEditWebTest extends WebTestCase
{
/**
* #covers ::edit
*/
public function testEdit():void
{
//...
$this->assertSomething();
}
}
And the tested Controller:
namespace App\Controller;
class UserEditController
{
public function edit() {
//..
}
protected function someOtherFn():void
{
//..
}
}
Now UnitTest says on code-coverate output:
$ utest --coverage-text
Classes: 23.41% (125/534)
Methods: 32.75% (1091/3331)
Lines: 31.58% (4799/15198)
App\Controller\Admin\User\UserEditController
Methods: 0.00% ( 0/ 2) Lines: 44.78% ( 30/ 67)
Q: What am I doing wrong?
Why is Methods on 0/2 ?
I also tried removing the #covers-Annotation from the test-method docblock, or adding the full namespace of the controller before the ::edit - nothing works.
I cleared the cache of the test-environment
Solution
I found out, that using the #covers-annotation is not required at all, actually. If everything is configured correctly, the tested classes, methods and lines should automatically being registered correctly.
In PhpStorm, you can run a "coverage test" which is an xdebug run that shows all code covered.
The annotation was not been taken into account, so I had to actually change my test so that more of the code is truly being tested - e.g. adding tests for each possible case inside a method.

PHPUnit marking test as risky when defining expectations on passed mock

I am trying to set test expectations on a mock object that is created in a data provider and passed to my test method. This is useful because I can reused my data provider across different test cases and have the tests define what to expect on the mock. However, phpunit marks this test as risky when the case passes, but correctly fails the test when it does not pass. Is this a known thing that cannot be done?
I am using phpunit v9.3
Here is a contrived example to show the problem:
<?php
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class Test extends TestCase
{
public function provideMock(): array
{
return [
[$this->createMock(\DateTime::class)],
];
}
/** #dataProvider provideMock */
public function testMockPasses(MockObject $mock): void
{
$mock->expects($this->once())->method('format')->with('Y-m-d');
$mock->format('Y-m-d');
}
/** #dataProvider provideMock */
public function testMockFails(MockObject $mock): void
{
$mock->expects($this->once())->method('format')->with('Y-m-d');
$mock->format('Y-m-');
}
}
I would expect this to work fine as I am just passing the object to the method - all internal php stuff.
Try running PHPUnit with --verbose key - it may tell more about the reason of marking the test as risky.

phpUnit test issue does not run [duplicate]

I'm just test playing with Php unit.
Here is my DependencyFailureTest class:
require_once '../vendor/autoload.php';
use PHPUnit\Framework\TestCase;
class DependencyFailureTest extends \PHPUnit\Framework\TestCase
{
public function testOne()
{
$this->assertTrue(false);
}
/**
* #depends testOne
*/
public function testTwo()
{
}
}
But on running the command phpunit --verbose DependencyFailureTest it throws
Argument #3 (No Value) of PHPUnit_TextUI_ResultPrinter::__construct() must be a value from "never", "auto" or "always".
Can anybody give an explanation for this issue?
It must be a configuration issue. I copied your code and ran it on the command line with verbose and it worked fine with version 5.4.6.
I would reinstall phpunit and ensure you have the latest version.
Also, their sample test case from their Getting Started page is:
<?php
use PHPUnit\Framework\TestCase;
class MoneyTest extends TestCase
{
// ...
public function testCanBeNegated()
{
// Arrange
$a = new Money(1);
// Act
$b = $a->negate();
// Assert
$this->assertEquals(-1, $b->getAmount());
}
// ...
}
https://phpunit.de/getting-started.html
Notice the difference in your extension usage, although I don't think it is an issue, if you use their declaration as stated, it helps to isolate the problem.
I ran into this. Was passing --colors=true, but that is incorrect.

phpunit throws "Argument #3 (No Value) of PHPUnit_TextUI_ResultPrinter::__construct() must be a value from "never", "auto" or "always""

I'm just test playing with Php unit.
Here is my DependencyFailureTest class:
require_once '../vendor/autoload.php';
use PHPUnit\Framework\TestCase;
class DependencyFailureTest extends \PHPUnit\Framework\TestCase
{
public function testOne()
{
$this->assertTrue(false);
}
/**
* #depends testOne
*/
public function testTwo()
{
}
}
But on running the command phpunit --verbose DependencyFailureTest it throws
Argument #3 (No Value) of PHPUnit_TextUI_ResultPrinter::__construct() must be a value from "never", "auto" or "always".
Can anybody give an explanation for this issue?
It must be a configuration issue. I copied your code and ran it on the command line with verbose and it worked fine with version 5.4.6.
I would reinstall phpunit and ensure you have the latest version.
Also, their sample test case from their Getting Started page is:
<?php
use PHPUnit\Framework\TestCase;
class MoneyTest extends TestCase
{
// ...
public function testCanBeNegated()
{
// Arrange
$a = new Money(1);
// Act
$b = $a->negate();
// Assert
$this->assertEquals(-1, $b->getAmount());
}
// ...
}
https://phpunit.de/getting-started.html
Notice the difference in your extension usage, although I don't think it is an issue, if you use their declaration as stated, it helps to isolate the problem.
I ran into this. Was passing --colors=true, but that is incorrect.

constructor breaks phpunit tests with providers

Here's a test PHPUnit test I wrote:
<?php
class MyTest extends PHPUnit_Framework_TestCase
{
public function __construct()
{
echo "starting tests\r\n";
parent::__construct();
}
public function provider()
{
return array(array('test'));
}
/**
* #dataProvider provider
*/
public function testProvider($var)
{
$this->assertEquals($var, $var);
//exit($var);
}
}
When I run it I get the following:
There was 1 error:
1) MyTest::testProvider
Missing argument 1 for MyTest::testProvider()
/home/myname/test.php:19
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
My question is... why? And what can I do about it?
In the actual unit tests I'm writing (the above is just a test demonstrating the problem) I'm testing a class with several different backend engines. I have an abstract class with a bunch of test cases and a protected class variable named $engine. I then have a bunch of classes that extend this abstract class and set $engine in the constructor. In each of the test methods in the abstract method $obj->setEngine($this->engine) is then called to test the specific engine in question. But this approach seems to break unit tests with providers and in lieu of that I'm not sure what I should be doing.
Any ideas?
Instead of implementing a constructor, you should use the static method setUpBeforeClass to create the $engine. The engine must be stored in a static property.
https://phpunit.de/manual/current/en/fixtures.html#fixtures.sharing-fixture

Categories