sub
sub

Reputation: 712

How can you create a Mock of a method that extends a sealed class?

I have created a sealed class as follows and created extension methods.

sealed class Result<S, E extends Exception> {
  const Result();
}

final class Success<S, E extends Exception> extends Result<S, E> {
  const Success({required this.value});
  final S value;
}

final class Failure<S, E extends Exception> extends Result<S, E> {
  const Failure({required this.exception});
  final E exception;
}

extension ResultExtension on Result<dynamic, Exception> {
  dynamic unwrap() {
    if (this is Success) {
      return (this as Success).value;
    } else {
      throw (this as Failure).exception;
    }
  }
}

Therefore, I have created the following method that uses this class.

  String execute() {
    try {
      final result = fetchText(); // return Result<String, Exception>
      return result.unwrap() as String;
    } on Exception catch (_) {
      rethrow;
    }
  }

And I have created unit tests like this.

    test('', () {
      // Arrange
      when(
        fetchText(),
      ).thenAnswer((_) => const Success(value: 'Success'));

      // Act
      final result = execute();

      // Assert
      expect(result, 'Success');
    });

And, the following error message is being displayed.

  MissingDummyValueError: Result<String, Exception>
  
  This means Mockito was not smart enough to generate a dummy value of type
  'Result<String, Exception>'. Please consider using either 'provideDummy' or 'provideDummyBuilder'
  functions to give Mockito a proper dummy value.
  
  Please note that due to implementation details Mockito sometimes needs users
  to provide dummy values for some types, even if they plan to explicitly stub
  all the called methods.

I believe it's because I haven't created a mock for unwrap(), but I have no idea how to create it. How can I create a mock for a method that extends a sealed class?

Upvotes: 4

Views: 2164

Answers (1)

burkinafaso3741
burkinafaso3741

Reputation: 1340

You need to provide it manually. Add this to the test. Mockito wasn't able to generate, but you can manually add a dummy instance:

read here

void main() {
    provideDummy<Result<String, Exception>>(const Success("value")); 

 // Result<String, Exception>>(const Success("value"))
 // that part changes according to your sealed class & sub classes


   setUp(() {
   // other intializations
   });

}

Upvotes: 7

Related Questions