jeudi 30 janvier 2020

Why does my Test not pass for passing a null List? [duplicate]

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;
        }

Aucun commentaire:

Enregistrer un commentaire