kenprogrammer's avatar

PHPUnit Test Doubles: Test passes without SUT

The following test passes WITHOUT the underlying SUT

public function testWithStub()
  {
        // Create a stub for the LoanCalculator class.
         $calculator = $this->getMockBuilder('Calculator')
                                             ->setMethods(['add'])
                                             ->getMock();
        
           // Configure the stub.
           $calculator->expects($this->any())
                                 ->method('add')
                                ->will($this->returnValue(6));
        
          $this->assertEquals(6, $calculator->add(100,100));
   }

The class being tested doesn't exist. Why is the test passing?

0 likes
7 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try giving it the full namespace (use App\SomeNamespace\Calculator; at the top of the test file)

$calculator = $this->getMockBuilder(Calculator::class)
1 like
kenprogrammer's avatar

@Sinnbeck I've imported an existing class using namespace. The test still passes even if the method being stubbed does'nt exist. The class has no method name 'add'

Sinnbeck's avatar

@kenprogrammer Yeah. It has been deprecated for this reason. If you check the source for the method, you will see this

@deprecated https://github.com/sebastianbergmann/phpunit/pull/3687

Use ->onlyMethods() instead. Or ->addMethods() if you want to add a method

1 like

Please or to participate in this conversation.