My class has a dependency which I mocked in my unit tests. I was getting a null reference exception in a place where it didn't make much sense to me.
I just realised it was because I didn't set up my mocked dependency. This dependency is tested but it doesn't connect to anything like file system or data sources.
I only wanted to test my new code in this new class but I guess in this case it is better not to mock at all.
Is this conclusion correct?
Mocking is bad because it can lead to overspecification of tests. Use stub if possible and avoid mock.
Unit tests are incredibly important to us as developers because they allow us to demonstrate the correctness of the code we've written. More importantly, unit tests allow us to make updates to our code base with confidence that we haven't broken anything.
What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.
Mocking means creating a fake version of an external or internal service that can stand in for the real one, helping your tests run more quickly and more reliably. When your implementation interacts with an object's properties, rather than its function or behavior, a mock can be used.
Correct. You should mock things that depend on anything persistent or external in order to prevent the test from depending on anything persistent or external.
If the dependency does not depend on anything persistent or external, the only benefit you gain from mocking it is that the test will work properly even if the dependency is wrong - but that's assuming the mock works properly. For that you need to either:
Write a mock that emulates the dependency completely.
Write a mock that emulates the dependency for the specific cases that will be used in the test.
The first option is outright ridiculous - why should your mock be any better than the original dependency? After all, it's safe to assume much more effort was invested in the original dependency than in the mock...
The second option means your mock knows the exact details of the implementation - otherwise you won't know how the implementation uses the dependency so you don't know how to mock those specific uses. This means the test does not serve one of the main purposes of unit tests - verifying that the code works properly after changes to the implementation.
The drawbacks of mocking are too big and the advantages are too small - especially considering that you can always run the dependency's tests to check if it works properly...
It sounds like it's working in your case, but it's not true in general that the only reason to stub or mock is to get external data sources and such out of your test's hair. Other reasons include
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With