raphire
raphire

Reputation: 318

Unit test of a child class in dart

I am able to write the unit test for the parent class, but I am stuck on the child class. How to write unit tests of a child class.

class Parent {

  SomeService _someService;
  SomeService get someService => _someService;
  
  Parent() {
    this._someService = SomeService();
  }
  
  Parent.withService(this._someService);

  Map<String, dynamic> getResult() {

    return _someService.getResult();
  }
}

class Child extends Parent {
  
  int useResult() {
   return someService.useResult();
  }
}

I am able to test the Parent class with mockito by mocking SomeService class. I had to use the constructor Parent.withService() for that. I am stuck at testing the methods of the child class. How to test the methods of child class? Thanks.

Upvotes: 0

Views: 354

Answers (1)

Christian
Christian

Reputation: 26387

I would make the service a named variable that can be passed into the class:

class Parent {    
  SomeService? _someService;
  SomeService get someService => _someService;
  
  Parent({SomeService? someService}) {
    this._someService = someService??SomeService();
  }

  Map<String, dynamic> getResult() {
    return _someService.getResult();
  }
}

class Child extends Parent {
  Child({SomeService? someService}):super(someService);
  
  int useResult() {
   return someService.useResult();
  }
}

Upvotes: 1

Related Questions