Stubbing and Mocking
Learn about stubs and mocks and why mocks are preferred over stubs.
The need for stubbing and mocking
In unit testing, we should be able to test every application layer independently. A test for the service layer should not be dependent on the data layer. We use stubbing and mocking to test a part of our application by mocking an external service or an application layer. There are different mocking frameworks available like Mockito, JMock, and EasyMock
Suppose we have a ExamService
class which has a findTotal()
method to perform the sum of an array. We have another class ExamRepository
that has a method to return data about student marks. In the findTotal()
method, we can fetch data using the ExamRepository
object and then find the total. Now every time the JUnit test runs, the ExamRepository
class will connect to a database and get marks’ data. This approach has two glaring issues. On one hand, it makes the test execution time longer, and on the other hand, it makes the test susceptible to failure in case the database connection is down. In such a scenario, our test will fail because of database connectivity issues and not because of any mistake in the logic of the code under test. To avoid this, we can either stub or mock the data source and simply test our code without interacting with the database.
In the same manner, if our application connects to a cloud service, we can mock the service instead of actually connecting to it every time.
We will create a method findTotal()
in the ExamService
class to find the total of an array. It uses the ExamRepository
class that returns an array of marks obtained by a student. Our method uses the data returned by the ExamRepository
class to find the total of the array.
Get hands-on with 1400+ tech skills courses.