John Davidson

php - Replace all class instances with stub

0 comments
Message:


I am testing a class, let's call it ClassUnderTest using another class, let's call it OtherClass. In my Test I do:


$OtherClassStub = $this->createStub(OtherClass::class);
$OtherClassStub->method(...)
->willReturn(...);
$ClassUnderTest->otherClass = $OtherClassStub;

That works. But when the $ClassUnderTest calls new OtherClass(), the original OtherClass class is created instead of the stub.


How can I achieve that every possible instance of OtherClass in the context of the test is replaced by the stub?



My Answer:
>getMockBuilder(OtherClass::class)
->disableOriginalConstructor()
->getMock();

$this->getMockBuilder(ClassUnderTest::class)
->setConstructorArgs([$OtherClassStub])
->getMock();

Rate this post

3 of 5 based on 3425 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us