Simple Unit Testing

This is a simple program that demonstrates some unit tests. Depending on your opinion or requirements unit testing is essential in testing code. I’m starting to learn the in’s and outs of unit testing standards, testing to pass, and testing to fail. This is a very simple gradebook console program. It doesn’t really do anything useful except demonstrate concepts. In this case unit testing.

Over the next few posts I’ll be using this same batch of code in different versions. I might not go over all the ways I’m doing things if it’s not in scope of what the blog post is about. If you want to see all of the source you can visit the source downloads page.

SolutionExplorer

 
GradeStatistics.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1.Grades
{
    public class GradeStatistics
    {
        // Fields
        public float AverageGrade;
        public float HighestGrade;
        public float LowestGrade;

        // Constructors
        public GradeStatistics()
        {
            // Setting the fields with values.
            HighestGrade = 0;
            LowestGrade = float.MaxValue;       // Setting the lowest grade to a really high number to check against.
        }
    }
}

This simple class has fields to hold the average, highest, and lowest grade in a grade book. When instantiated the highest grade and lowest grade are set. The highest grade set to a value of zero. The lowest grade is set to a maximum value initally. This way it can be compared to an actual value that is gauranteed to be lower. I’m leaving the calculation of the average grade up to the GradeBook class.

 
Gradebook.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1.Grades
{
    public class GradeBook
    {
        private List<float> _grades;

        public string Name;

        public GradeBook()
        {
            _grades = new List<float>();
        }

        public void AddGrade(float grade)
        {
            // Adding some validation logic before adding the grade to the collection.
            if (grade >= 0 && grade <= 100)
                _grades.Add(grade);
        }

        public GradeStatistics ComputeStatictics()
        {
            // Creating an instance variable of the class to return.
            GradeStatistics stats = new GradeStatistics();

            // Now to find the average, highest, and lowest grade in the list.
            float sum = 0f;
            foreach (float grade in _grades)
            {
                // Calculating the highest and lowest grade using built-in .NET methods.
                // Comparing the current grade in the loop to the highest grade. If greater then assign the new value.
                stats.HighestGrade = Math.Max(grade, stats.HighestGrade);

                // Comparing the current grade in the loop to the lowest grade. If lower then assign the new value.
                stats.LowestGrade = Math.Min(grade, stats.LowestGrade);
                
                // Adding numbers to the sum variable.
                sum += grade;
            }

            // Calculating the average grade.
            stats.AverageGrade = sum / _grades.Count();     // Normally this would be encased in a try/catch. Possible divide by zero exception.
            return stats;
        }
    }
}

This class holds the grade book list, name, computes the statistics on the grades in the gradebook, and adds grades to the grade book.

 
Program.cs code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1.Grades
{
    class Program
    {
        static void Main(string[] args)
        {
            // Demonstrating reference types. Basically a pointer to the objects place in memory.
            GradeBook book = new GradeBook();
            book.AddGrade(91);
            book.AddGrade(89.5f);
            book.AddGrade(75f);

            // Calling a method that will compute statistics and return me a value.
            // Then that value will be stored in a class variable.
            GradeStatistics stats = book.ComputeStatictics();
            Console.WriteLine(stats.HighestGrade);
            Console.WriteLine(stats.LowestGrade);
            Console.WriteLine(stats.AverageGrade);
            Console.ReadLine();
        }
    }
}

I’ve kept this class pretty simple thru the demonstration of instantiation and method calls. Creating the gradebook, adding grades to the gradebook, and computing the statistics on the grades in the gradebook.

 
GradeBookTests.cs code

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using _1.Grades;

namespace Grades.Tests
{
    [TestClass]
    public class GradeBookTests
    {
        [TestMethod]
        public void CalculateHighestGradePass()
        {
            GradeBook book = new GradeBook();
            book.AddGrade(50f);
            book.AddGrade(90f);
            book.AddGrade(100f);

            GradeStatistics stats = book.ComputeStatictics();

            // Checking to see if this test reports back as passed/true. That this is the highest grade.
            Assert.AreEqual(100f, stats.HighestGrade);
        }
        [TestMethod]
        public void CalculateHighestGradeFail()
        {
            GradeBook book = new GradeBook();
            book.AddGrade(50f);
            book.AddGrade(90f);
            book.AddGrade(100f);

            GradeStatistics stats = book.ComputeStatictics();

            // Checking to see if this test reports back as failed/false. That this is not the highest grade.
            Assert.AreEqual(90f, stats.HighestGrade);
        }

        [TestMethod]
        public void CalulateLowestGradePass()
        {
            GradeBook book = new GradeBook();
            book.AddGrade(50f);
            book.AddGrade(90f);
            book.AddGrade(100f);

            GradeStatistics stats = book.ComputeStatictics();

            // Checking to see if this test reports back as passed/true. That this is the highest grade.
            Assert.AreEqual(50f, stats.LowestGrade);
        }

        [TestMethod]
        public void CalculateLowestGradeFail()
        {
            GradeBook book = new GradeBook();
            book.AddGrade(50f);
            book.AddGrade(90f); 
            book.AddGrade(100f);

            GradeStatistics stats = book.ComputeStatictics();

            // Checking to see if this test reports back as passed/true. That this is the highest grade.
            Assert.AreEqual(50f, stats.HighestGrade);
        }

        [TestMethod]
        public void PassByValuePass()
        {
            GradeBook book = new GradeBook();
            book.Name = "Not Set";
            SetName(book);

            // Checking to see if this test reports back as passed/true. That the book name was set to this value.
            Assert.AreEqual("Name Set", book.Name);
        }

        [TestMethod]
        public void PassByValueFail()
        {
            GradeBook book = new GradeBook();
            book.Name = "Not Set";
            SetName(book);

            // Checking to see if the test reports back as failed/false. The book name is not set to this value.
            Assert.AreEqual("This can't be right", book.Name);
        }

        // Private method used to demostrate passing by value in a unit test.
        private void SetName(GradeBook book)
        {
            book.Name = "Name Set";
        }
    }
}

This is unit test class. Here I’m testing for passing and failing of various items. Examples include testing to make sure highest grade is calculated correctly pass/fail, lowest grade pass/fail, and a pass by value and reference pass/fail.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s