Search code examples
unit-testingservicestackinversion-of-control

How best to unit test a ServiceStack service that uses IServiceGateway to call other internal services


I've been following the guidelines here - https://docs.servicestack.net/testing

I'm trying to do unit testing rather than integration, just to cut down the level of mocking and other complexities.

Some of my services call some of my other services, via the recommended IServiceGateway API, e.g. Gateway.Send(MyRequest).

However when running tests i'm getting System.NotImplementedException: 'Unable to resolve service 'GetMyContentRequest''.

I've used container.RegisterAutoWired() which is the service that handles this request.

I'm not sure where to go next. I really don't want to have to start again setting up an integration test pattern.


Solution

  • You're likely going to continually run into issues if you try to execute Service Integrations as unit tests instead of Integration tests which would start in a verified valid state.

    But for Gateway Requests, they're executed using an IServiceGateway which you can choose to override by implementing GetServiceGateway() in your custom AppHost with a custom implementation, or by registering an IServiceGatewayFactory or IServiceGateway in your IOC, here's the default implementation:

    public virtual IServiceGateway GetServiceGateway(IRequest req)
    {
        if (req == null)
            throw new ArgumentNullException(nameof(req));
    
        var factory = Container.TryResolve<IServiceGatewayFactory>();
        return factory != null ? factory.GetServiceGateway(req) 
            : Container.TryResolve<IServiceGateway>()
            ?? new InProcessServiceGateway(req);
    }