Reputation: 395
I am mocking a repository with the annotation @mock and then saving some data to the repository in the test class. Is the data really getting stored in the repository?
In another class when the same data is fetched it is showing not found. How will I test my class if the data is not stored in the repository?
Upvotes: 1
Views: 1362
Reputation: 140613
Most likely, when you use the @Mock
annotation correctly in your test code, your mocking framework will come and instantiate something for you under that name:
@Mock
WhatEver someWhatEver;
In other words: when the above "executes", someWhatEver
will reference some object that conforms to the "API" that the WhatEver
class provides.
Meaning: you can call all methods that exist on that class. And nothing will happen. Because someWhatEver
isn't a instance of your real production class. It is something that looks like it.
Thus, the real answer is: you step back, and you research the whole topic. There is no point in doing "unit testing" using some mocking framework without "understanding" what you are doing. The tutorial by vogella is a good starting point.
Upvotes: 2
Reputation: 139
When we want to do a Service Unit Test in SpringBoot Application We have not gone use Real DataBase just we need to Mock DataBases.
Similarly When u want to do Unit Test any External Serivce in Your class Just U can Mock that External Service call.
A Mockito mock allows us to stub a method call. That means we can stub a method to return a specific object. For example, we can mock a Spring Data JPA repository in a service class to stub a getBooks() method of the repository to return a Book object.
Upvotes: 0
Reputation:
Mocking is a way to encapsulate your unit tests. If you want to test a service method you are not interested if the repository is working. For this you will write repository tests. Therefore you mock the repository call and tell which result should be returned to test your method in all possible situation. The mock itself is a proxy, therefore there the data which are you saved are not really safed in your database. This has the advantage that you haven´t to start your whole context and the tests are much faster.
Upvotes: 0