Home > Enterprise >  How to test MaterialStateProperty values?
How to test MaterialStateProperty values?

Time:07-19

I have a button with a specific elevation, set as an argument:

        child: ElevatedButton(
          key: const Key('MyButton'),
          onPressed: () {},
          child: Text('My Button'),
          style: ButtonStyle(
            elevation: MaterialStateProperty.all<double>(2.0),
              ),
            ), ...

I would like to test the elevation value. The snippet I've wrote is below:

      final button = tester
          .widget<ElevatedButton>(find.byKey(Key('NewSessionsElevatedButton')));
      expect(button.style.elevation, MaterialStateProperty.all<double>(2.0));

However, the exception below is raised in the test, telling both values are equal, but it breaks anyway:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: _MaterialStatePropertyAll<double>:<MaterialStateProperty.all(2.0)>
  Actual: _MaterialStatePropertyAll<double>:<MaterialStateProperty.all(2.0)>

I've read the tests for this class in the repository, but they are not clear. How can I test MaterialStateProperty values?

CodePudding user response:

I've just got hit by this issue myself.

For your specific test, this would be the code:

final button = tester.widget<ElevatedButton(find.byKey(Key('MyButton')));
final elevation = button.style!.elevation;

expect(elevation!.resolve(<MaterialState>{}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.hovered}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.focused}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.pressed}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.dragged}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.selected}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.disabled}), 2.0);
expect(elevation.resolve(<MaterialState>{MaterialState.error}), 2.0);

You need use resolve in order to retrieve the exact state for which to test. The properties of the ButtonStyles are sets, so you need to get the value for each state you want to test.

Hope it helped.

  • Related