-2

I am working in C# building a form application. I have a method that takes in a type of List and returns a hashtable. I am trying to throw an argument exception if the the list is null. My program works the way it should and returns the results I need.

This is the error

Message:   Expected: <System.Exception>
  But was:  <System.NullReferenceException: Object reference not set to an instance of an object.
   at WordOccurenceCalculator.WordCalculator.CalculateOccurrences(List`1 List)
public void CalculateOccurrencesShouldThrowException() {

            List<string> list = null;
            WordCalculator calc = new WordCalculator();

            Assert.Throws<Exception>(delegate { calc.CalculateOccurrences(list); });
}


 public Hashtable CalculateOccurrences(List<string> List)
        {
            if ( List.Count == 0)
            {
                throw new System.ArgumentException("Invalid Input");
            }

            if (List == null)
            {
                throw new System.ArgumentException("Invalid Input");
            }


            Hashtable table = new Hashtable();
            int counter = 1;
            int j = 1;
            for (int i = 0; i < List.Count; i++)
            {
                for(j = i + 1 ; j <= List.Count; j++)
                {
                   if(j < List.Count){
                if (List[i] == List[j])
                {
                    counter++;
                }
            }
                }
                if (!table.Contains(List[i]))
                {
                    table.Add(List[i], counter);

                }
                counter = 1;

            }

            return table;
        }

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
ZST
  • 39
  • 1
  • 6
  • So what's the question? Where is your test code? – Badhon Jain Jan 31 '20 at 05:09
  • @AlexeiLevenkov I am not sure I understand your question. Can you please clarify it for me. Thank you. – ZST Jan 31 '20 at 05:22
  • 1
    check `Assert.Throws` [documentation](https://github.com/nunit/docs/wiki/Assert.Throws#exact-versus-derived-types), the exact type should be thrown, not a derived type – jalsh Jan 31 '20 at 06:00

1 Answers1

-1

you are checking null after trying to access count property of null list. You would get exception from there too. Try the bellow.

      if (List == null)
        {
            throw new System.ArgumentException("Invalid Input");
        }

       if ( List.Count == 0)
        {
            throw new System.ArgumentException("Invalid Input");
        }
Badhon Jain
  • 938
  • 6
  • 20
  • 38