Perform the following steps:
- Create a new unit testing project by right-clicking on the solution and then clicking on Add New Project. In the Add New Project window, choose Test in the list of Project Type and choose xUnit Test Project(.NET Core) in the list of projects, as shown here:
- Ensure that you have chosen the xUnit Test Project(.NET Core) in the Package Manager console and run the following commands:
- Install the Moq NuGet package using the Install-Package Moq command
- Install the ASP.NET Core package using the Install-Package Microsoft.AspNetCore command
- In the unit test project, we also need the reference to the Azure Function that we want to run the unit tests. Add a reference to the FunctionAppInVisualStudio application so that we can call the HTTP trigger's Run method from our unit tests.
- Add all the required namespaces to the Unit Test class, as follows: and replace the default code with the following code. The following code mocks the requests, creates a Query string collection with a key named name, assigns a value of Praveen Sreeram, executes the function, gets the response, and then compares the response value with an expected value:
using FunctionAppInVisualStudio;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
using Moq;
using System;
using System.Collections.Generic;
using Xunit;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace AzureFunctions.Tests
{
public class ShouldExecuteAzureFunctions
{
[Fact]
public async Task WithAQueryString()
{
var httpRequestMock = new Mock<HttpRequest>();
var LogMock = new Mock<ILogger>();
var queryStringParams = new Dictionary<String, StringValues>();
httpRequestMock.Setup(req => req.Query).Returns(new QueryCollection(queryStringParams));
queryStringParams.Add("name", "Praveen Sreeram");
var result = await HTTPTriggerCSharpFromVS.Run(httpRequestMock.Object,LogMock.Object);
var resultObject = (OkObjectResult)result;
Assert.Equal("Hello, Praveen Sreeram", resultObject.Value);
}
}
}
- Now, right-click on the unit test and click on Run test(s), as shown in the following screenshot:
If everything is set up correctly, your tests should pass, as shown in the following screenshot:
That's it. We have learnt how to write a basic unit test case for a HTTP Trigger.