I am new to unit testing and fairly new to c# and would really appreciate some help with how to write a unit test to ensure the logic in the AddGrade method is working. So basically if the grade is >=0 and <=100 then the grade is valid and it will be added, anything else isn't and it should display an error in the console.
I have seen another post about unit testing an if-else statement in c# and tried working this out from that but It confused me if I am honest. I have looked around online etc and tried a lot of different things to try and figure this out but I find it hard sometimes to apply peoples example to my code so I thought it best just to post my code and get some help, any help would be greatly appreciated :)
I am using Xunit for the unit tests. This project runs in the console.
This is the program class with the main method
using System;
using System.Collections.Generic;
namespace GradeBook
{
class Program
{
static void Main(string[] args)
{
var book = new Book("Dave's");
//add grade to the book
book.AddGrade(90.5);
book.AddGrade(80.5);
book.AddGrade(70.5);
book.AddGrade(60.5);
var stats = book.GetStatistics();
Console.WriteLine($"This Gradebooks name is {book.Name}");
Console.WriteLine($"The highest grade is {stats.High:N1}");
Console.WriteLine($"The lowest grade is {stats.Low:N1}");
Console.WriteLine($"The average grade is {stats.Average:N1}");//N1,N2 etc. is number of decimal places
}
}
}
This is the book class where the AddGrade method is I want to write the unit test for
using System;
using System.Collections.Generic;
namespace GradeBook
{
public class Book
{
public Book(string name)
{
grades = new List<double>();
Name = name;
}
public void AddGrade(double grade)
{
if (grade >= 0 && grade <= 100)
{
grades.Add(grade);
}
else
{
Console.WriteLine("Please enter a value between 0 and 100");
}
}
public Statistics GetStatistics()
{
var result = new Statistics();
result.Average = 0.0;
result.High = double.MinValue;
result.Low = double.MaxValue;
foreach (var grade in grades)
{
Console.WriteLine($"{Name} grade is: {grade}");
result.Low = Math.Min(grade, result.Low);
result.High = Math.Max(grade, result.High);
result.Average += grade;
}
result.Average /= grades.Count;
return result;
}
private List<double> grades = new List<double>() { };
public string Name;
}
}
This is the Statistics class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeBook
{
public class Statistics
{
public double Average;
public double High;
public double Low;
}
}
This is where I am writing the unit test for this
using System;
using System.Collections.Generic;
using Xunit;
namespace GradeBook.Tests
{
public class BookTests
{
[Fact]
public void BookGradeIsValid()
{
var book = new Book("");
book.AddGrade(105);
}
}
}