0

I am reading data from a JSON file which is placed App_Data folder, my method is like below.

    public List<CounterModel> ReadData()
    {
        string file = HttpContext.Current.Server.MapPath("~/App_Data/counter.json");
        string Json = File.ReadAllText(file);
        List<CounterModel> items = JsonConvert.DeserializeObject<List<CounterModel>>(Json);
        var res = items.OrderByDescending(x => x.year).ToList();
        return res;
    }

I have written test method using nunit to test ReadData method like below,

    [TestFixture]
    public class ReadJsonTest
    {
        [Test]
        public void ReadDataTestMain()
        {
            ReadFile rf = new ReadFile();
            int output = rf.ReadData().Count();
            Assert.IsTrue(output > 0, "The file is not having any data");

        }
    }

When I try to debug the test method(ReadDataTestMain) it is throwing error in my actual method(ReadData) in the very first line of HttpContext that Object reference not to set as an instance of object. How can I unit test my method?

ali
  • 31
  • 5
  • I know why it is throwing null exception but how can I test the method which is reading data from App_Data folder? – ali Jan 29 '21 at 09:30
  • This is not really a dup of NullReference, but you shouldn't unit test this logic at all, if you split the ReadData function into units of work, one method to read the file as text, one method to parse the text, then you unit test the parse method with a _known_ input. – Chris Schaller Jan 30 '21 at 13:45

0 Answers0