First we created a couple of classes to test. A Grade Class to store grade information and a GPA class that stores grades in a list and has two methods one to calculate GPA and one to calculate a straight average.
Grade Class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class Grade { public string ClassName { get; set; } public int Credits { get; set; } public double GradePoint { get; set; } } }
GPA Class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class GPA { public ListGrades { get; set; } public GPA() { Grades = new List (); } public void addGrade(Grade g) { Grades.Add(g); } public double CalculateGPA() { int totalCredits = 0; double totalWeight = 0; foreach(Grade g in Grades) { totalCredits += g.Credits; totalWeight += g.Credits * g.GradePoint; } return totalWeight / totalCredits; } public double StraightAverage() { double totalGrades = 0; foreach(Grade g in Grades) { totalGrades += g.GradePoint; } return totalGrades / Grades.Count(); } } }
Next we right clicked on the solution and added a new project. We chose Test and Unit Test. Next we added a reference to the GPA project so we could talk to its classes. (It is important that they be public.)
Here is the Test class
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ConsoleApplication2; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { GPA gpa = new GPA(); [TestMethod] public void TestGPA() { AddSomeClasses(); double g = gpa.CalculateGPA(); Assert.AreEqual(39.5 / 13, g); } [TestMethod] public void TestStraightAverage() { AddSomeClasses(); double avg = gpa.StraightAverage(); Assert.AreEqual(9.5 / 3, avg); } private void AddSomeClasses() { Grade g1 = new Grade(); g1.Credits = 5; g1.GradePoint = 2; gpa.addGrade(g1); Grade g2 = new Grade(); g2.Credits = 3; g2.GradePoint = 4; gpa.addGrade(g2); Grade g3 = new Grade(); g3.Credits = 5; g3.GradePoint = 3.5; gpa.addGrade(g3); } } }
No comments:
Post a Comment