Skip to content

TestUtils (flutter/packages) should be deleted/tests refactored #146457

Closed
flutter/packages
#6490
@matanlurey

Description

@matanlurey

The camera_android plugin makes use of a TestUtils class with the following behavior:

public class TestUtils {
  public static <T> void setPrivateField(T instance, String fieldName, Object newValue) {
    try {
      Field field = instance.getClass().getDeclaredField(fieldName);
      field.setAccessible(true);
      field.set(instance, newValue);
    } catch (Exception e) {
      Assert.fail("Unable to mock private field: " + fieldName);
    }
  }

  public static <T> Object getPrivateField(T instance, String fieldName) {
    try {
      Field field = instance.getClass().getDeclaredField(fieldName);
      field.setAccessible(true);
      return field.get(instance);
    } catch (Exception e) {
      Assert.fail("Unable to mock private field: " + fieldName);
      return null;
    }
  }
}

This is ... not a good pattern. If the field needs to be made public, it should be made public (or package-private) and @VisibleForTesting used. That pattern itself should be kept to a minimum, and instead the APIs should have good inherent testability/make use of patterns like dependency injection.

This is blocking my work on flutter/packages#6461, and while I could work around it, I'd be spending a reasonable amount of time working around a bad pattern. If @reidbaker and team are on board, I'd rather spend my time helping you all delete this pattern.

Metadata

Metadata

Assignees

No one assigned

    Labels

    c: tech-debtTechnical debt, code quality, testing, etc.p: cameraThe camera pluginpackageflutter/packages repository. See also p: labels.team-androidOwned by Android platform team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions