Mock vs. Stub vs. SpyMockMocks are the objects that store method calls. It referred to as the dynamic wrappers for dependencies used in the tests. It is used to record and verify the interaction between the Java classes. A mock is known as the most powerful and flexible version of the test doubles. We use a method for mocking is called mock(). The main function of using mocks is that it gives full control over the behavior of the mocked objects. The mock objects are generally used for behavior verification. The term behavior means to check the correct methods and paths that are applied to the objects. Mocks are mostly created by using a library or a mocking framework like Mockito, JMock, and EasyMock. It is used for testing a large suite of tests where stubs are not sufficient. One of the essential functions of mock is, we can verify how many times a given method is called. The following code snippet shows how to use mock(). StubStubs are the objects that hold predefined data and uses it to give responses during tests. In other words, a stub is an object that resembles a real object with the minimum number of methods needed for a test. Stubs are used when we don't want to use objects that would give a response with real data. A stub is referred to as the lightest, and the most static version of the test doubles. The main functions of the stubs are:
SpySpies are known as partially mock objects. It means spy creates a partial object or a half dummy of the real object by stubbing or spying the real ones. In spying, the real object remains unchanged, and we just spy some specific methods of it. In other words, we take the existing (real) object and replace or spy only some of its methods. Spies are useful when we have a huge class full of methods, and we want to mock certain methods. In this scenario, we should prefer using spies rather than mocks and stubs. It calls the real method behavior, if the methods are not stubbed. In Mockito, spy() method is used for creating spy objects. It allows us to call the normal methods of the real object. The following code snippet shows how to use the spy() method. Difference between Stub and Mock
Following are some differences between the mock and spy:
In our previous tutorials, we have discussed some examples of stubbing, mocking, and spying. For better understanding the difference between stubbing, mocking, and spying, go through the examples. Next TopicSpying or Mocking Abstract Classes |