skip to Main Content

im testing this method here

  @override
  Future<List<dynamic>> makeRequest(ApiRequestParams params) async {
    try {
      final request = await _repository.get(params);

      if (request == null) {
        throw Exception('Whoops');
      }

      // Go on...
    } catch (e) {
      rethrow;
    }
  }

When repository itself doesn’t throw, but returns null, I want to makeRequest to throw. But when testing it, I assumme that since I’m not throwing in the when method, makeRequest is throwing and stopping there. So is there a way that I can throw something outside of when and catching it?

My test block

    test('When api returns null, should throw exception', () async {
      // stub
      when(() => repository.get(requestParams))
          .thenAnswer((_) => Future.value(null));

      // arrange
      final result = await usecase.makeRequest(requestParams);

      // assert
      verify(() => repository.get(requestParams)).called(1);
      expect(result, throwsA(isA<Exception>()));
    });
  }); 

2

Answers


  1. Chosen as BEST ANSWER

    Solution

    I found the solution when reading this question

    Doesn't work:

      // arrange
      final result = await usecase.makeRequest(requestParams);
    
      // assert
      verify(() => repository.get(requestParams)).called(1);
      expect(result, throwsA(isA<Exception>()));
    

    Works:

      // act
      final pokemonCall = pokemonUsecase.fetchPokemons(requestParams);
    
      // assert
      verify(() => repository.get(requestParams)).called(1);
      await expectLater(pokemonCall, throwsA(isA<DioException>()));
    

    Not sure why but using expectLater instead of await and then expect works.


  2. In Mocktail, you can catch exceptions that were not thrown in a when method by using the thenThrow method to specify the exception that should be thrown when the mocked method is called with certain parameters. If the method is called with different parameters, it will throw an exception by default.

    Here’s an example of how you can catch exceptions that were not thrown in a when method using Mocktail in Flutter:

    import 'package:mocktail/mocktail.dart';
    import 'package:flutter_test/flutter_test.dart';
    
    class MockService extends Mock implements SomeService {}
    
    class SomeService {
      Future<int> fetchData(int id) async {
        // Some asynchronous operation
        if (id == 1) {
          return 42;
        } else {
          throw Exception('Failed to fetch data');
        }
      }
    }
    
    void main() {
      late SomeService service;
    
      setUp(() {
        service = MockService();
      });
    
      test('test fetchData', () async {
        // Mocking the fetchData method
        when(() => service.fetchData(1)).thenAnswer((_) async => 42);
        when(() => service.fetchData(2)).thenThrow(Exception('Failed to fetch data'));
    
        // Calling fetchData with valid parameter
        expect(await service.fetchData(1), 42);
    
        // Calling fetchData with invalid parameter should throw an exception
        expect(() async => await service.fetchData(2), throwsException);
      });
    }
    

    In this example:

    • We mock the fetchData method of SomeService class using the when method. When fetchData is called with 1, it will return 42. When fetchData is called with 2, it will throw an exception.
    • We then test the fetchData method by calling it with valid and invalid parameters. We expect that calling it with 1 will return 42, and calling it with 2 will throw an exception as specified in the when method.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search