Tuesday, May 27, 2014

Unit Testing Visual Studio.

I create a unit test to test the CalcualteGPA method in the GPACalculator. First right click on the solution and add a new test project.

Right click on the new Test Project. Add a reference to the project you want to test

The Solution should look like this

Add code to test the method

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using GradePointCalculator;
using System.Collections.Generic;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        GPACalculator gp = new GPACalculator();
     
        [TestMethod]
        public void TestMethod1()
        {
            //addGrades
            CreateGradeList();
            //call the method
            double gpa = gp.GetGpa();
            //assert the value you expect, and
            //the actual value. (rounded because hard to match all the decimals)
            Assert.AreEqual(3.5, Math.Round(gpa, 2));
            
        }

        private void CreateGradeList()
        {
            //add a couple of grades
            Grade g1 = new Grade();
            g1.ClassName = "ITC 110";
            g1.Credits = 2;
            g1.GradePoint = 1;

            gp.AddGrade(g1);

            Grade g2 = new Grade();
            g2.ClassName = "ITC 220";
            g2.Credits = 5;
            g2.GradePoint = 4;
            gp.AddGrade(g2);

            
        }
    }
}

Go to the Test menu in Visual Studio and choosr tun all tests. A test explorer will show up. Here is the result for a passed test

I changed the value so that the result will fail. Here is a failed result

No comments:

Post a Comment