Unit Testing GetxController Unit Testing GetxController flutter flutter

Unit Testing GetxController


This question has now been answered in the GetX docs.

Pasted from the docs:

Tests

You can test your controllers like any other class, including their lifecycles:

class Controller extends GetxController {  @override  void onInit() {    super.onInit();    //Change value to name2    name.value = 'name2';  }  @override  void onClose() {    name.value = '';    super.onClose();  }  final name = 'name1'.obs;  void changeName() => name.value = 'name3';}void main() {  test('''Test the state of the reactive variable "name" across all of its lifecycles''',      () {    /// You can test the controller without the lifecycle,    /// but it's not recommended unless you're not using    ///  GetX dependency injection    final controller = Controller();    expect(controller.name.value, 'name1');    /// If you are using it, you can test everything,    /// including the state of the application after each lifecycle.    Get.put(controller); // onInit was called    expect(controller.name.value, 'name2');    /// Test your functions    controller.changeName();    expect(controller.name.value, 'name3');    /// onClose was called    Get.delete<Controller>();    expect(controller.name.value, '');  });}

Mockito or mocktail

If you need to mock your GetxController/GetxService, you should extend GetxController, and mixin it with Mock, that way

class NotificationServiceMock extends GetxService with Mock implements NotificationService {}

Not exactly intuitive, is it?


Try changing your fake controller definition to:

class FakeAuthController extends GetxController with Fake implements AuthController {}

Not sure this works for Fake, but I just fixed a similar issue with Mock with it.