How to unit test Handlers and Behaviors
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?
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.
Closing for now. Feel free to reopen if you have any further questions.