Search code examples
flutterdartflutter-test

Why expect(Future.value(true), Future.value(true)) has fail result in flutter test?


So I feel a bit confused with this matcher.

Why does this test returning fail?

expect(Future.value(true),Future.value(true));

I thought it was the same value and the matcher should be returning success for that test.


Solution

  • They are different objects which are compared using the hashcode operator ==, not by hashCode. However, the default operator == implementation compares object identity. Which will be different because they are not the same object.

    If you await the futures the values will be compared and it will pass.

      test('test', () async {
        print(Future.value(true).hashCode);
        print(Future.value(true).hashCode);
        expect(await Future.value(true), await Future.value(true));
      });
    

    https://api.flutter.dev/flutter/dart-core/Object/operator_equals.html

    Edit: To answer your other question:

    Do you know how to compare 2 same classes? I just try expect(ClassA(), ClassA()) still returning fail test. How to make expect(ClassA(), ClassA()) to pass?

    You're kind of using the expect in the wrong way. If you want to know if the class is a specific kind you can do this:

    test('test', () async {
        final ClassA classAInstance = ClassA();
        expect(classAInstance, isA<ClassA>());
        expect(classAInstance == classAInstance, true);
      });
    

    Thank you jamesdlin for correcting me on the hashcode.