Avoid testing using mocks

Flutter tips Published on

Why Mocks Can Make Testing Hard

Mocks often force your tests to know exactly how your code works inside. This means if you change the internal steps of your code, even if the final result is the same, your tests might break.

Test What Your Code Does, Not How

The best way to test lets you change your code's inner workings without breaking the tests. Instead of checking if certain functions were called on a mock object, focus on the outcome or behavior of your code.

Easy Refactoring

When your tests focus on results, you can improve or rewrite parts of your code internally (refactor) and your tests will still pass as long as the code still does the right thing from the outside. This makes maintaining and improving your code much simpler.

An Example Shown

The example in the image shows testing if a notification was successfully received and its content, rather than checking if a specific 'send' method was called on a mocked object.

Move Beyond Restrictive Mocking

Frameworks or approaches that require you to mock and verify every single interaction can make your tests fragile and difficult to update. Focusing on behavior frees you from this constraint.

Save 3 months of work

Create your app using our 6 years of making Flutter apps and more than 50+ apps

kickstarter for flutter apps

Frequently Asked Questions

Why is testing implementation details with mocks a problem?

It makes your tests fragile. If you change the internal steps of your code (refactoring), your tests can fail even if the code still works correctly from the user's perspective.

What is 'testing behavior'?

Testing behavior means checking the outcome or result of your code's action, rather than checking the specific sequence of steps or method calls it made internally.

Does this mean I should never use mocks?

Not necessarily never, but for many types of tests, especially integration or unit tests focusing on logic flow, testing the final outcome or effect is often more robust and easier to maintain than heavy mocking.

How does this help with refactoring?

Since your tests don't depend on the internal structure, you can change how your code works internally without having to rewrite your tests, as long as the code still produces the same correct result.

Read more
You may also be interested in
Center a form Without hiding fields when keyboard is open  blog card image
Center a form Without hiding fields when keyboard is open
Published on 2025-05-13T07:05:30.629Z
Benchmark a function within a test  blog card image
Benchmark a function within a test
Published on 2025-05-12T12:24:19.613Z
ApparenceKit is a flutter template generator tool by Apparence.io © 2025.
All rights reserved