Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

flutter - How to test nulls using mockito?

I am using mockito 4.1.3 , and here I have some test class:

import 'package:flutter_test/flutter_test.dart';
import 'package:ghinbli_app/models/film_model.dart';
import 'package:ghinbli_app/network/ghibli_films.dart';
import 'package:mockito/mockito.dart';

class MockClient extends Mock implements GhibliFilms {
  @override
  Future<List<FilmModel>> getFilms() async{
    return null;
  }
}

void main() {
  final GhibliFilms ghibliMock = MockClient();
  test('If API call was unsuccessful and data received is null', () {

    expect(ghibliMock.getFilms(), null);
  });
}

Inside the MockClient class, I am overriding a method called getFilms() and returning null to simulate a situation when a call to some API returns null as data.


A problem

When I try to check if getFilms() actually returns a null value my test will fail with this error (probably because of the return type of getFilms()):

Expected: <null>
     Actual: <Instance of 'Future<List<FilmModel>>'>

How can I check and test that the data from getFilms() is actually null, what am I doing wrong?

question from:https://stackoverflow.com/questions/65858172/how-to-test-nulls-using-mockito

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I've tested your code and got same error as you. After making these changes everything runs fine, try it yourself.

class MockClient extends Mock implements GhibliFilms {
  @override
  Future<List<FilmModel>> getFilms() async {
    return Future.value(null); // this is not that important
  }
}

void main() {
  final GhibliFilms ghibliMock = MockClient();

  // async/await here was important
  test('If API call was unsuccessful and data received is null', () async { 
    expect(await ghibliMock.getFilms(), null); 
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...