0

I am writing a unit test cases fro Azure function.In my function app configuration section i have added my connection string.

When the azure function runs in azure below line of code is working fine.

var connStr = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;

If i am calling the azure function from unit test case this line is throwing exception. "object reference not set to an instance of an object".

Form unit test case how i can execute this line of code.(using Moq).

Test Method :

[TestMethod]
public async Task GetDataFromAzureSQL_Test()
    {


         var req = new HttpRequestMessage();

        var obj = new Modeltest
        {
            id = 1,
            name ="",
            location=""

        };

        var content = new StringContent(JsonConvert.SerializeObject(obj).ToString(), Encoding.UTF8, "application/json");
        req.Content = content;
        var result = await Function.Function1.Run(req, new Mock<ILogger>().Object);
        Assert.IsTrue("OK" == result.StatusCode.ToString());

    }
Elina
  • 139
  • 3
  • 9
  • Does this answer your question? [How to mock ConfigurationManager.AppSettings with moq](https://stackoverflow.com/questions/9486087/how-to-mock-configurationmanager-appsettings-with-moq) – yaakov Feb 20 '20 at 08:20
  • No,Test project we have to call the Azure function and above mentioned line of code should cover in the code coverage. – Elina Feb 20 '20 at 08:53
  • @Elina could you please post the code of your unit test and the corresponding azure unction ? Thanks – Christos Feb 20 '20 at 09:40
  • in .net core I always create a base class and put something like this: var builder = new ConfigurationBuilder() .AddJsonFile($"{AppDomain.CurrentDomain.BaseDirectory}appsettings.json"); _configuration = builder.Build(); then var connectionString = _configuration.GetConnectionString("DefaultConnection") – Netferret Feb 20 '20 at 10:45
  • I think you've MISSED the Appconfig.xml in your test project (you're in a full framework app cause ConfigurationManager doesn't exist in .net core) – federico scamuzzi Feb 20 '20 at 11:51
  • Appconfig.xml is present in the test project – Elina Feb 20 '20 at 12:06
  • Usually in Azure Functions (and .Net Core in general) you inject an `IConfiguration` instead, and use that to get your connection strings (and of course it's easily mockable). – sellotape Feb 20 '20 at 13:24
  • can you please give me some sample code – Elina Feb 21 '20 at 04:14
  • Add AppSetting file in your test project and put dummy value – Pankaj Rawat Feb 21 '20 at 08:45

0 Answers0