Search Unity

Testing API services using base classes/interfaces

Discussion in 'Scripting' started by mahdiii, Apr 6, 2019.

  1. mahdiii

    mahdiii

    Joined:
    Oct 30, 2014
    Posts:
    856
    Hi. Suppose, For example, I want to call a leaderboard service API.

    Code (CSharp):
    1.  
    2. public async void GetLeaderboard(){
    3.      var data=await new LeaderboardService().GetLeaderboard(top,count,LeaderboardName);
    4. }
    However I intend to utilize interfaces, so I can test services using fake/forged data and do not always need a real remote server.

    How do you handle it?

    1- Defining base abstract scriptableObjects for services with different implementations? (They can be serialized and I can utilize inspector serialization)
    2- Using Dependency injection frameworks
    3- Creating services in other classes and pass them into this class (Method injection)
    Code (CSharp):
    1. ILeaderboardService _service;
    2. public void Initialize(ILeaderboardService service){
    3.    _service=service;
    4. }
    5. ------------------------------------------------------------------------------------
    6. public class LeaderboardServiceCreator:MonoBehaviour{
    7.    [SerializeField] private LeaderboardController _leaderboardController;
    8.    private void OnEnable(){          
    9.         _leaderboardController.Initialize(new LeaderboardService());
    10. //       _leaderboardController.Initialize(new TestLeaderboardService());
    11.    }
    12. }
    13.  
     
    Last edited: Apr 6, 2019