Immediate.Handlers icon indicating copy to clipboard operation
Immediate.Handlers copied to clipboard

How to unit test Handlers and Behaviors

Open hag8194 opened this issue 1 year ago • 1 comments

Scenario:

I have an Azure Function Http Trigger which I wanna test:

public class HttpFunction(CommandName.Handler handler)
{
    [Function(nameof(HttpFunction))]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(
            AuthorizationLevel.Function,
            "post",
            Route = "http-function")]
        HttpRequestData req)
    {
        ...
    }
}

And my issue here is that I'm not able to Substitute/Mock the CommandName.Handler on my test:

[TestClass]
public class HttpFunctionTest
{
    private CommandName.Handler _handler = null!;
    private HttpFunction _customSection = null!;
    
    [TestInitialize]
    public void Initialize()
    {
        _handler = Substitute.For<CommandName.Handler>();  //This fails because the constructor doesn't match this definition
        _customSection = new HttpFunction(_handler);
    }

    ...
}

I'm using MSTest and NSubstitute packages.

Question: How can I substitute/mock the CommandName.Handler in order to unit test my function code?

hag8194 avatar May 16 '24 16:05 hag8194

First, I generally avoid unit testing the external layer. I've never found knowing that the function itself works useful, without knowing that the command is also useful.

That said, what you're looking for is IHandler<..., ...>, where the type arguments match the type arguments for CommandName.Handler.

viceroypenguin avatar May 16 '24 16:05 viceroypenguin

Closing for now. Feel free to reopen if you have any further questions.

viceroypenguin avatar May 18 '24 02:05 viceroypenguin