Search code examples
flutterdartmockitoflutter-mockito

How to fix type 'Null' is not a subtype of type 'int'? (Mockito Unit test)


The error message you're encountering, "type 'Null' is not a subtype of type 'int'," suggests that there might be an issue with the way you are creating or using the MockCalculator instance in my test.

How to fix type 'Null' is not a subtype of type 'int'? (Mockito Unit test)

lib/calculator

    class Calculator {
  // This class represents a simple calculator.

  // The `add` method takes two integers `a` and `b` as input and returns their sum.
  int add(int a, int b) {
    return a + b; // Calculate the sum of `a` and `b` and return it.
  }
}

test/calculator_mock_test.dart

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'calculator_test.dart';


void main() {
  group('Calculator', () {
    test('addition', () {
      // Create a mock Calculator instance
      final mockCalculator = MockCalculator();

      // Define the behavior for the 'add' method
      when(mockCalculator.add(2, 3)).thenReturn(5);

      // Test the 'add' method using the mock
      final result = mockCalculator.add(2, 3);

      // Verify that the 'add' method was called with the expected arguments
      verify(mockCalculator.add(2, 3));

      // Verify that the result matches the expected result
      expect(result, 5);
    });
  });
}

Here is an error:

type 'Null' is not a subtype of type 'int'
test\calculator_test.dart 5:7         MockCalculator.add
test\calculator_mock_test.dart 13:27  main.<fn>.<fn>

enter image description here

How to fix type 'Null' is not a subtype of type 'int'? (Mockito Unit test).


Solution

  • Make the int in function parameter, Nullable.