How to test a void function in Dart? - flutter

I am new to unit tests in Dart/Flutter and I would like to write a test for a void function. When functions return something I am writing a test like this:
test('Gets user save', () async {
final userSave = await mockSource!.getUserSave();
expect(userSave!.age, equals(20));
});
In such a scenario like above expect can be used since getUserSave function returns a user model.
How about checking if test passes of fails for a void/Future function like below? I can not use expect because it does not return a value.
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.clear();
}
I use flutter_test and mockito for testing.

Typically a void function will produce a side effect of some sort. When writing a test for a void function, I would check whatever state is effected by the void function before and after calling the function to be sure that the desired side effect has occurred.
In this specific case, you are calling clear on a DatabaseClient. I don't know the specifics of the DatabaseClient api, but I would construct a test where the client contains some data before calling clear, and then check that the data is no longer there after calling clear.
Something along the lines of this:
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.add(SOMEDATA);
expect(mockDBClient.hasData, true);
mockDBClient.clear();
expect(mockDBClient.hasData, false);
}

you can add nullable variable and assign variable value in method, after call method check if this varaible isNotNull
like this:
test('Gets user save', () async {
await mockSource?.getUserSave();
final userSave=mockSource.user;
expect(userSave,isNotNull );
});

testing a function that return void :
expect(
() async => await functionThatReturnsVoid(),
isA<void>(),
);

Related

GetX doesn't accept method parameters either

I cannot use the ".obs" property variables that I have created as parameters in my api service methods. and it gives the error The prefix 'coinTwo' can't be used here because it is shadowed by a local declaration.
Try renaming either the prefix or the local declaration.
I wrote the problem in getx, but they did not understand the problem.
I would appreciate it if you could take a look at my issue on github.
İssue link: text
I would appreciate it if you could take a look at my issue on github.
İssue link: text
Your problem is in the declaration of getOrderBookData
Instead of
getOrderBookData(coinOne.value, coinTwo.value) async {
...
you should either have
getOrderBookData() async {
...
//Do stuff with coinOne.value, coinTwo.value
...
OR
getOrderBookData(String firstCoin, String secondCoin) async {
coinOne.value = firstCoin;
coinTwo.value = secondCoin;
...
Edit
Seeing your post on GetX's Github, it looks like you're missing some basic understanding on how functions and methods work.
The code you wrote is the equivalent of the following method signature :
getOrderBookData("aValue", "anotherValue") async {
and it doesn't makes any sense.
Your method's signature should only declare the parameters it's expecting and their type.
You can also define a default value for those parameters if needed.
getOrderBookData({String firstCoin = coinOne.value, String secondCoin = coinTwo.value}) async {
in function declarations you just tell what type it is, and not actual values
So either do
getOrderbookData(String one, String two) async {
var res = await api.fetchOrderBookData(one, two);
purchase.value = res.result!.buy!;
sales.value = res.result!.sell!;
}
or hardcode it to always use coinOne and coinTwo and give no parameters
getOrderbookData() async {
var res = await api.fetchOrderBookData(coinOne.value, coinTwo.value);
purchase.value = res.result!.buy!;
sales.value = res.result!.sell!;
}
Make these changes and the error will be gone.
First, make a minor change to your getOrderBookData method:
void getOrderBookData() async {...} // Don't pass any parameter here.
And then make a change to your onInit method too.
#override
void onInit() {
getOrderBookData();
super.onInit();
}

Does a function that calls a Future needs to be a Future too?

I have a function that calls a Future in it. Now I am not sure if the first function needs to be a future too to await for the data. Here is my code:
FireBaseHandler handler = FireBaseHandler();
saveRows() {
handler.saveRows(plan.planId, plan.rows); ///this is a future
}
In my FireBaseHandler class I have this Future:
final CollectionReference usersCol =
FirebaseFirestore.instance.collection('users');
Future saveRows(String id, data) async {
return await usersCol.doc(myUser.uid).collection('plans').doc(id)
.update({'rows': data});
}
So does the first function needs to be a Future too?
You can have async function inside a sync function. But this way you lose ability to await for the result. And await is allowed only in functions marked as async, which leads us to Future as a the result of that function. So, yes, if you need to wait for the result, both functions have to be Future functions.
Edit:
If you need your wrapper function to be sync, but still be able to retrieve the result from inner async function, you can use a callback:
saveRows(Function(dynamic) callback) {
handler.saveRows(plan.planId, plan.rows).then((result){
callback(result);
});
}
This way the result will be retrieved at any point of time after calling the function (the code is not awaited)

While the inner method async does the outer method has to be async?

I have an async method. Can I call it from an non-async method? Like the following
My method
void method() async{
await 'something'
}
Case 1
onPressed:() {
method();
}
Case 2
onPressed:() async{
await method();
}
Which of the above is correct? It seems to me two of them is OK. However, the second one I think works much more slower, am I wrong?
In general, the caller of an async function must also be asynchronous if it wants to wait for the call to complete. This makes asynchronous-ness contagious.
In your case, your async function is a "fire-and-forget" function; callers cannot wait for it to complete, so it doesn't matter. Your second case (with await method()) is wrong because you should use await only on Future/FutureOr, but method returns void, so there nothing to wait for. (The Dart analyzer would warn you about this if you have the await_only_futures lint enabled.)
You also could simplify your code further by using a tear-off instead of creating an unnecessary closure:
onPressed: method

Test Flutter Facebook Firebase Login

I would like to test the facebookLogin() method on my app, but I can't set it properly.
Code reference
This is my test :
test(
"should return FirebaseUser when called loginWithFacebook",
() async {
// arrange
when(mockFacebookLogin.login()).thenAnswer((realInvocation) async => tToken);
when(FacebookAuthProvider.credential("token-id")).thenReturn(tCredential);
// act
final result = await repository.loginWithFacebook();
// assert
expect(result, Right(tFirebaseUser));
verify(mockFacebookLogin.login());
},
);
I get this error: Bad state: No method stub was called from within 'when()'. Was a real method called, or perhaps an extension method? on when(FacebookAuthProvider.credential("token-id")).thenReturn(tCredential);
I read that this error shows because I'm trying to mock a static method and I need to convert it to a non-static method.

Why async keyword function without await keyword in Dart?

I saw many people's code use async keyword in a function without an await keyword in the function body. Even some official flutter example code do this. I have no idea why. What is the point? Is this a mistake or having a purpose?
Normally, I just remove the async keyword from those code and everything will run without any problems. Can some dart expert clarify that if there is a purpose for a function which has the async keyword but NO await keyword? Or is this just their mistake?
async is sometimes used to simplify code.
Here are some examples:
Future<int> f1() async => 1;
Future<int> f1() => Future.value(1);
Future<void> f2() async {
throw Error();
}
Future<void> f2() {
return Future.error(Error());
}
According to official Dart Language tour, async executes synchronously until it finds await keyword :
Note: Although an async function might perform time-consuming operations, it doesn’t wait for those operations. Instead, the async function executes only until it encounters its first await expression (details). Then it returns a Future object, resuming execution only after the await expression completes.