Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a method in the same class being tested

I want to mock a method in the same class that I am testing.

ClassA {
   function hardToTest($arg) {
      // difficult to test code
   }

   function underTest() {
      return $this->hardToTest('foo');
   }
}

I was thinking that I could use reflection to do this, but maybe it is just a sign that I should move hardToTest into another object.

like image 448
james Avatar asked Apr 26 '11 19:04

james


People also ask

How do you mock another method that is being tested in the same class?

We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.

What is difference between @mock and @injectmock?

@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.

How do you mock a method in jest?

The simplest and most common way of creating a mock is jest. fn() method. If no implementation is provided, it will return the undefined value. There is plenty of helpful methods on returned Jest mock to control its input, output and implementation.


1 Answers

This test will succeed if underTest() passes 'foo' to hardToTest(). This is known as a partial mock in PHPUnit's documentation because you are mocking only some of the methods.

ClassATest {     function testUnderTest() {         $mock = $this->getMock('ClassA', ['hardToTest']);         $mock->expects($this->once())              ->method('hardToTest')              ->with('foo');         $mock->underTest();     } } 

I agree with your instincts that this need may be a code smell telling you that this class is doing too much.

PHPUnit 5.4+

Since getMock() was deprecated in 5.4, use getMockBuilder() instead:.

$mock = $this->getMockBuilder('ClassA')              ->setMethods(['hardToTest'])    // onlyMethods in 8.4+              ->ge‌​tMock(); 
like image 144
David Harkness Avatar answered Nov 15 '22 11:11

David Harkness