Finished Testing Your Code, Refactoring for Testability

test_your_code
Jason Zhu 2021-02-17 12:33:05 +00:00
parent 41bf0f3824
commit b6387e0e8c
4 changed files with 38 additions and 15 deletions

View File

@ -3,6 +3,12 @@ using System.Collections.Generic;
namespace GradeBook namespace GradeBook
{ {
// public class Statistics
// {
// public double Average;
// public double highGrade;
// public double lowGrade;
// }
public class Book public class Book
{ {
private List<double> grades; private List<double> grades;
@ -19,24 +25,22 @@ namespace GradeBook
this.grades.Add(grade); this.grades.Add(grade);
} }
public void ShowStaticstics() public Statistics GetStatistics()
{ {
var result = new Statistics();
result.Average = 0.0;
result.highGrade = double.MinValue;
result.lowGrade = double.MaxValue;
double result = 0; foreach (var grade in this.grades)
var highGrade = double.MinValue;
var lowGrade = double.MaxValue;
foreach (var number in this.grades)
{ {
highGrade = Math.Max(number, highGrade); result.lowGrade = Math.Min(grade, result.lowGrade);
lowGrade = Math.Min(number, lowGrade); result.highGrade = Math.Max(grade, result.highGrade);
result += number; result.Average += grade;
} }
result /= grades.Count;
Console.WriteLine($"The average grade is {result:N1}"); result.Average /= grades.Count;
Console.WriteLine($"The highest grade is {highGrade:N1}"); return result;
Console.WriteLine($"The lowest grade is {lowGrade:N1}");
} }
} }

View File

@ -12,7 +12,12 @@ namespace GradeBook
book.AddGrade(89.1); book.AddGrade(89.1);
book.AddGrade(90.5); book.AddGrade(90.5);
book.AddGrade(87.2); book.AddGrade(87.2);
book.ShowStaticstics();
var stats = book.GetStatistics();
Console.WriteLine($"The lowest grade is {stats.lowGrade}");
Console.WriteLine($"The highest grade is {stats.highGrade}");
Console.WriteLine($"The average grade is {stats.Average:N1}");
} }
} }
} }

View File

@ -0,0 +1,9 @@
namespace GradeBook
{
public class Statistics
{
public double Average;
public double highGrade;
public double lowGrade;
}
}

View File

@ -16,7 +16,12 @@ namespace GradeBook.Tests
book.AddGrade(77.3); book.AddGrade(77.3);
// act // act
book.ShowStaticstics(); var result = book.GetStatistics();
// assert
Assert.Equal(85.6, result.Average, 1);
Assert.Equal(90.5, result.highGrade);
Assert.Equal(77.3, result.lowGrade);
} }
} }
} }