New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mocking final classes? #635
Comments
We cannot support mocking a final class.
Questions like this are better asked at a user forum like StackOverflow or Discord. |
For those coming across this: consider using the 'interface' modifier instead of 'final' for classes that are visible to package users. It does allow Mockito to mock it, and it still prevents the class from being extended (which is usually the bigger concern for package developers). |
but most sense we use mock for a 3rd lib... |
Yes that's the same issue @gdutpxz as I encountered. As @781flyingdutchman suggested replacing The main problem is that most plugin developers don't really think about these user written tests. Most plugins are not mockable by default because they use global variables/functions. But now even those plugins won't be mockable which use final classes, if the devs don't know about this issue. Well final classes are much worse, because global functions can be wrapped, but final classes... well they could be wrapped too, but meh. Now in mockito 5.4.1's changelog there is a line:
Not sure what does that mean yet, but mockito can't do anything more about this sadly. |
Yes, you can't mock The thing is, if you own this class, it's your call, you can either remove If you don't own this class, it's a bit trickier. You can create your wrapper class that contains the class you want to mock and just passes all requests to it. Then you can mock this wrapper class. Of course, for this to be useful, you would have to rewrite all your code to use your wrapper, instead of using the original class directly. Unfortunately that's the only way, if original class' authors are not willing to make a mockable interface. |
Just to summarize, there are 2 options for this:
|
Hello,
Dart 3 introduced some class modifiers, like
final
. A class marked withfinal
cannot be extended and mocks are basically created by extending a class. So currently I get the following error when trying to mock a final class:In java there is a package called mockito-inline which somehow solves mocking final classes (don't know how).
So my question:
Do anyone see a way to make it possible to mock final classes in dart mockito?
How I ran into this: A plugin author marked some of the plugin's classes final which I previously mocked for tests. So I guess its not a good idea to mark plugin classes final, right?
The text was updated successfully, but these errors were encountered: