Service Fabric Unit Testing and Dependency Injection

前端 未结 2 1081
独厮守ぢ
独厮守ぢ 2021-02-12 22:43

I can\'t test a Reliable Service/Actor by just calling it\'s constructor and then test it\'s methods. var testService = new SomeService(); throws a NullReferenceExc

2条回答
  •  野的像风
    2021-02-12 23:08

    For mocking the state manager in Reliable Actors, you can do something like this:

    private readonly IActorStateManager _stateManager;
    
    public MyActor(IActorStateManager stateManager = null)
    {
        _stateManager = stateManager ?? this.StateManager;
    }
    

    Actually, the StateManager isn't yet initialized at this time. We can get it when OnActivateAsync is called:

    private IActorStateManager _stateManager;
    
    // Unit tests can inject mock here.
    public MyActor(IActorStateManager stateManager = null)
    {
        _stateManager = stateManager;
    }
    
    protected override async Task OnActivateAsync()
    {
        if (_stateManager == null)
        {
            _stateManager = StateManager;
        }
    }
    

    Just make sure to always use _stateManager in the rest of the code instead of this.StateManager.

提交回复
热议问题