How to verify a method inside a method is called in mockito - flutter

I was doing some unit testing in flutter with mockito, and I feels unable to verify a method is called within another method. The code I've written so far as follows,
The class I want to test
class A {
void doSomething() {
callMe();
}
void callMe() {}
}
Mocked class
class MockA extends Mock implements A {}
The test I wrote,
test("Test method is called", () {
A a = new MockA();
a.doSomething();
verify(a.callMe()).called(1);
});
When I run the above test I am getting an error
No matching calls. All calls: MockA.doSomething()
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
If i verify doSomething is called it works, but for a call on callMe within doSomething doesn't work. Is this the default behavior or am I doing something wrong? Please note I need to verify the callMe() method is called when doSomething() is called.

You mocked A and replaced it with MockA. Mocks have no implementation. MockA.doSomething() does nothing and does not and cannot call MockA.callMe().
That A.doSomething() calls A.callMe() should be considered an implementation detail of of doSomething(); making a test rely on that would tightly couple the test to the specific implementation and would be brittle.
You can't use a mock to verify the implementation of the thing being mocked. If you want to verify the implementation of A.doSomething(), you instead should use an actual object and verify observable properties on that object.
But if you still really want to do this, then you would need to modify A to not call methods on itself and to instead call methods on a provided object (i.e., "dependency injection"). For example:
class A {
final late A a;
A({A? a}) {
this.a = a ?? this;
}
void doSomething() {
a.callMe();
}
void callMe() {}
}
test("Test method is called", () {
var mockA = MockA();
var actualA = A(a: mockA);
actualA.doSomething();
verify(mockA.callMe()).called(1);
});
It's a bit unusual for a class to depend on a mock of itself, however, and it would not scale if you then want to verify calls made by callMe().
Another approach that would scale better (but with significantly more work) would be to create your own fake class that tracks method calls:
class TrackedA implements A {
int doSomethingCallCount = 0;
int callMeCallCount = 0;
#override
void doSomething() {
doSomethingCallCount += 1;
super.doSomething();
}
#override
void callMe() {
callMeCallCount += 1;
super.callMe();
}
}
But again, that's very brittle, and I would not recommend it.

Related

Override/mock library functions for dart/flutter testing

I was wondering if there is a way to override library functions so they don't fire or just return something else.
import 'package:foo_package/exposing_foo_function.dart';
class TestableClass {
bool bar() {
return foo(); //foo is from the imported library
}
}
Test:
void main() {
test('TestableClass.bar() when foo_package.foo() returns false', () {
TestableClass testableClass = TestableClass();
// Something to make foo_package.foo() return false.
expect(testableClass.bar(), isFalse);
});
}
Things like mockito work by creating mock classes that implement the interface of the mocked class. That doesn't work for global and static functions, however.
What you instead can do is to avoid calling those global/static functions directly and instead call them through an extra level of indirection. For example:
import 'package:foo_package/exposing_foo_function.dart' as foo_package;
class TestableClass {
final bool Function() foo;
TestableClass({this.foo = foo_package.foo});
bool bar() {
return foo();
}
}
and then to test:
void main() {
test('TestableClass.bar() when foo_package.foo() returns false', () {
bool fakeFoo() => false;
TestableClass testableClass = TestableClass(foo: fakeFoo);
expect(testableClass.bar(), isFalse);
});
}
A similar approach is to wrap the global/static functions as instance methods of a class:
import 'package:foo_package/exposing_foo_function.dart' as foo_package;
class FooManager {
bool foo() => foo_package.foo();
}
var fooManager = FooManager();
class TestableClass {
bool bar() {
return fooManager.foo();
}
}
and then your tests can mock FooManager like any other class and set fooManager to the mocked version. (Or if you prefer dependency inversion to global variables, passing your mocked version of FooManager to TestableClass as a construction argument.)
Of course, all of the above will help only for your own calls that go through your wrappers. It won't help if code you don't control calls those functions. In that case, your best course of action might be to complain to the function's author about lack of testability.

async/await problem when extend super class

I need to set the order of execution of my methods on the constructor of my supper class because i have a multiple class that extends from this supper class and the order is the same on all of them (take advantage of abstract class), but i am facing a strange problem where i get a result of a variable before the finishing of the future, this is a simulation code of my above description, you can try it on dartpad.dev:
abstract class SuperClass {
bool _success;
bool get isSuccess => _success;
set setSuccess(bool success) => this._success = success;
SuperClass() {
//checkLogin();
runCode();
//sendRequest();
}
runCode() async {
await doSomething();
}
Future<void> doSomething();
}
class SubClass extends SuperClass {
String text;
#override
Future<void> doSomething() async {
text = await Future.delayed(Duration(seconds: 2), () => '2 sec of getting data');
if (text.isNotEmpty) {
setSuccess = true;
print(text);
}
print('value of success is "$isSuccess" from the overriding method');
}
}
void main() async {
SubClass subClass = new SubClass();
// if (subClass.isSuccess) // how can i get success from the sub class
// do somthing else
print('value of success is "${subClass.isSuccess}"');
}
the result is :
value of success is "null"
2 sec of getting data
value of success is "true" from the overriding method
My question is why i get the value of the variable from the super class while i am running the future method before it and read it from the sub class ?
Did i miss something or how i can handle this logic ?
you need another method in the abstract class, when creating an object from the subclass, calling abstract class constructor automatically, you are calling "doSomething" override method in the constructor by "runCode" method, but since "doSomething" method is override method It will be called automatically in subclasses, So you need another method
If your question is about why you get the print in this order rather than:
2 sec of getting data
value of success is "true" from the overriding method
value of success is "true"
that is just because you call the async function runCode() in the constructor of SuperClass which is implicitly called when you create a SubClass as the latter inherits from the former. Since the method is async and you are not awaitint it, the method starts running on a different thread and code execution is not stoped there waiting for the runCode() method to return.
This means that runCode() starts executing in a different thread and immediately after that, the SuperClass constructor returns, the SubClass method (which implicitly called the former) also returns, and then your print statement from main executes. Since these steps take less than two seconds to execute, they finish executing before the rest of runCode()
Instead, you can remove the runCode() from the abstract class constructor and call the doSomething() method after initializing:
void main() async {
SubClass subClass = new SubClass();
await subClass.doSomething();
print('value of success is "${subClass.isSuccess}"');
}

What is the best way to mock 3rd party library's static method with Mockito in flutter

The approach I am following now is creating a wrapper around the class providing the static method, and then mocking this wrapper instead of mocking the real class, as in:
class TestClass {
final ThirdPartyClassWrapper _thirdPartyClassWrapper;
TestClass(this._thirdPartyClassWrapper);
void someMethod() {
_thirdPartyClassWrapper.doSomething();
}
}
class ThirdPartyClass {
static void doSomething() {}
}
class ThirdPartyClassWrapper {
void doSomething() {
ThirdPartyClass.doSomething();
}
}
//now I can mock the class and control the behaviour of the method
//but there is alot of boilerplate code
class MockThirdPartyClassWrapper extends Mock implements ThirdPartyClassWrapper{}
But as you see a lot of boilerplate is introduced.
So is there a better way to solve the problem?

Flutter, Dart. Create anonymous class

Maybe it's really dumb question. But I cannot believe there is no resources, where it's described. Even from the official documentation. What I'm trying to do, it's create Anonymous class for the next function.
How to create Anonymous class in Dart with custom function something like next in Kotlin?
Handler(Looper.getMainLooper()).post(Runnable() {
#override
open fun run() {
//...
}
private fun local() {
//....
}
})
Dart does not support creating an anonymous class.
What you're trying to do is not possible.
On the other hand, you can create anonymous functions. So you could use that to mimic an anonymous class.
The idea is to add a constructor of your abstract class, that defer its implementation to callbacks.
abstract class Event {
void run();
}
class _AnonymousEvent implements Event {
_AnonymousEvent({void run()}): _run = run;
final void Function() _run;
#override
void run() => _run();
}
Event createAnonymousEvent() {
return _AnonymousEvent(
run: () => print('run'),
);
}
It's not strictly the same as an anonymous class and is closer to the decorator pattern. But it should cover most use-cases.
This is an alternative way, but not fully equivalent:
Problem, e.g.:
I would like to implement OnChildClickListener inline in my code without class. For this method:
void setOnChildClickListener(OnChildClickListener listener) {
...
}
Instead of this:
abstract class OnChildClickListener {
bool onChildClick(int groupPosition, int childPosition);
}
use this:
typedef OnChildClickListener = Function(int groupPosition, int childPosition);
And in code you can implement it in this way:
listView.setOnChildClickListener((int groupPosition, int childPosition) {
// your code here
});
In other words do not use abstract class, but use typedef.

In TypeScript, how to prevent a method from being called on derived class?

There are three classes.
// in external library, which I don't want to modify
class ComponentBase {
// I want calling this to be disallowed
forceUpdate() {}
}
class ComponentBase_MyVersion extends ComponentBase {
// I want subclasses to always call this, instead of forceUpdate()
Update() {}
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// I want this to be disallowed
this.forceUpdate();
// forcing the subclass to call this instead
this.Update();
}
}
How can I accomplish this, with changes only to ComponentBase_MyVersion?
Is there a way to "hide" a base-class member?
Or perhaps a way to override the definition -- like with the "new" keyword in C# -- letting me mangle the method definition to at least make warnings appear when attempting to call it?
The OOP does not allow you to do this kind of method cancellation. You can impleement this funcion on your class with an Exception like you suggested, or use a composition: https://en.wikipedia.org/wiki/Composition_over_inheritance
Example 1:
class ComponentBase {
forceUpdate() {}
}
class ComponentBase_MyVersion extends ComponentBase {
Update() {}
forceUpdate() {
throw new Error("Do not call this. Call Update() instead.");
}
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// wil raise an exception
this.forceUpdate();
this.Update();
}
}
Example 2 (composition):
class ComponentBase {
forceUpdate() {}
}
class ComponentBase_MyVersion {
private _component: ComponentBase = ...;
Update() {}
// expose _component desired members ...
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// compilation error
this.forceUpdate();
this.Update();
}
}
I hope I helped.
Encapsulate implementation by replacing inheritance with composition Delegation Pattern
You can do this by adding the private access modifier on the forceUpdate method. This will result in all the subclasses being unable to access forceUpdate. However TypeScript does not support package access modifiers, but you can do this by replacing inheritance with composition.
class ComponentBase {
forceUpdate() {
}
}
class ComponentBase_MyVersion {
// Replace inheritance with composition.
private component: ComponentBase;
Update() {
this.component.forceUpdate();
}
}
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// Now subclass can't access forceUpdate method
this.Update();
}
}
Use a symbol in order to prevent external access to the method.
If you don't want to replace inheritance with composition, you can use Symbol to define a method. If your target is es5 you must configure tsconfig.json compilerOptions.lib to include es2015.symbol. Because every symbol is unique, any external module will not be able to obtain the symbol and access the method.
// libs.ts
let forceUpdate = Symbol("forceUpdate");
export class ComponentBase {
[forceUpdate]() {
}
}
export default class ComponentBase_MyVersion extends ComponentBase {
Update() {
this[forceUpdate]();
}
}
// test.ts
import ComponentBase_MyVersion from "./libs";
class MyComponent extends ComponentBase_MyVersion {
DoSomething() {
// Now subclass can't access the forceUpdate method.
this.Update();
}
}
I found a way that seems to work -- that is, which causes warnings to appear when someone attempts to call forceUpdate() on a subclass instance.
forceUpdate(_: ()=>"Do not call this. Call Update() instead.") {
throw new Error("Do not call this. Call Update() instead.");
}
Now when I write new MyComponent().forceUpdate(), I get a compiler error, with the warning message containing a description telling me to use Update() instead.
EDIT: Apparently this only works because the base class already had this definition:
forceUpdate(callBack?: () => any): void;
If instead the base method is defined with no arguments originally (as in the OP), the above solution doesn't work.
However, if you have a case like mine (where there's an optional property like that, which you can narrow the return-type of), it works fine. (not sure if this return-type-narrowing is a bug, or intended)